Module:core.guarded_eval

3 Classes

classIPython.core.guarded_eval.EvaluationContext(locals:dict,globals:dict,evaluation:Literal['forbidden','minimal','limited','unsafe','dangerous']='forbidden',in_subscript:bool=False,auto_import:collections.abc.Callable[[collections.abc.Sequence[str]],module]|None=None,policy_overrides:dict=<factory>,transient_locals:dict=<factory>,class_transients:dict|None=None,instance_arg_name:str|None=None,current_value:ast.AST|None=None)

Bases:object

auto_import:Callable[[Sequence[str]],ModuleType]|None=None

Auto import method

class_transients:dict|None=None

Transients of class level

current_value:AST|None=None

Currently associated valueUseful for adding items to _Duck on annotated assignment

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

Evaluation policy identifier

globals:dict

Global namespace

in_subscript:bool=False

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

instance_arg_name:str|None=None

Instance variable name used in the method definition

locals:dict

Local namespace

policy_overrides:dict

Overrides for evaluation policy

replace(**changes)

Return a new copy of the context, with specified changes

transient_locals:dict

Transient local namespace used to store mocks

classIPython.core.guarded_eval.GuardRejection

Bases:Exception

Exception raised when guard rejects evaluation attempt.

classIPython.core.guarded_eval.ImpersonatingDuck

Bases:object

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

3 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 toforbiddenno evaluation will be performed; if it is set todangerousstandardeval() will be used; finally, for any other,policyeval_node() will be called on parsed AST.

IPython.core.guarded_eval.get_policy(context:EvaluationContext)EvaluationPolicy
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 (classsth:...)

  • function definitions (defsth:...)

  • variable assignments (x=1)

  • augmented assignments (x+=1)

  • deletions (delx)

Does not evaluate operations which do not return values:

  • assertions (assertx)

  • pass (pass)

  • imports (importx)

  • control flow:

    • conditionals (ifx:) except for ternary IfExp (aifxelseb)

    • loops (for andwhile)

    • 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.