Evaluating Python code without any preparsing

class sage.misc.python.Python

Bases: object

Allows for evaluating a chunk of code without any preparsing.

eval(x, globals, locals=None)

Evaluate x with given globals; locals is completely ignored.

This is specifically meant for evaluating code blocks with %python in the notebook.


  • x – a string

  • globals – a dictionary

  • locals – completely IGNORED


sage: from sage.misc.python import Python
sage: python = Python()
sage: python.eval('2+2', globals())

Any variables that are set during evaluation of the block will propagate to the globals dictionary.

sage: python.eval('a=5\nb=7\na+b', globals())
sage: b

The locals variable is ignored – it is there only for completeness. It is ignored since otherwise the following will not work:

sage: python.eval("def foo():\n   return 'foo'\nprint(foo())\ndef mumble():\n    print('mumble {}'.format(foo()))\nmumble()", globals())
mumble foo
sage: mumble
<function mumble at ...>