Important

This documentation covers IPython versions 6.0 and higher. Beginning with version 6.0, IPython stopped supporting compatibility with Python versions lower than 3.3 including all versions of Python 2.7.

If you are looking for an IPython version compatible with Python 2.7, please use the IPython 5.x LTS release and refer to its documentation (LTS is the long term support release).

Module: core.guarded_eval

3 Classes

class IPython.core.guarded_eval.EvaluationContext(locals, globals, evaluation, in_subscript)

Bases: NamedTuple

evaluation: Literal['forbidden', 'minimal', 'limited', 'unsafe', 'dangerous']

Evaluation policy identifier

globals: dict

Global namespace

in_subscript: bool

Whether the evalution of code takes place inside of a subscript. Useful for evaluating :-1, 'col' in df[:-1, 'col'].

locals: dict

Local namespace

class IPython.core.guarded_eval.GuardRejection

Bases: Exception

Exception raised when guard rejects evaluation attempt.

class IPython.core.guarded_eval.ImpersonatingDuck

Bases: object

A dummy class used to create objects of other classes without calling their __init__

2 Functions

IPython.core.guarded_eval.guarded_eval(code: str, context: EvaluationContext)

Evaluate provided code in the evaluation context.

If evaluation policy given by context is set to forbidden no evaluation will be performed; if it is set to dangerous standard eval() will be used; finally, for any other, policy eval_node() will be called on parsed AST.

IPython.core.guarded_eval.eval_node(node: AST | None, context: EvaluationContext)

Evaluate AST node in provided context.

Applies evaluation restrictions defined in the context. Currently does not support evaluation of functions with keyword arguments.

Does not evaluate actions that always have side effects:

  • class definitions (class sth: ...)

  • function definitions (def sth: ...)

  • variable assignments (x = 1)

  • augmented assignments (x += 1)

  • deletions (del x)

Does not evaluate operations which do not return values:

  • assertions (assert x)

  • pass (pass)

  • imports (import x)

  • control flow:

    • conditionals (if x:) except for ternary IfExp (a if x else b)

    • loops (for and while)

    • exception handling

The purpose of this function is to guard against unwanted side-effects; it does not give guarantees on protection from malicious code execution.