Evaluating Python code without any preparsing - Utilities

Skip to content
Back to top
View this page
Edit this page

# Evaluating Python code without any preparsing

class sage.misc.python.Python

  Bases: `object`

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

    INPUT:

    - `x` – string

    - `globals` – dictionary

    - `locals` – completely IGNORED

    EXAMPLES:

    Sage

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

    Python

        >>> from sage.all import *
        >>> from sage.misc.python import Python
        >>> python = Python()
        >>> python.eval('2+2', globals())
        4
        ''

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

    Sage

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

    [Python]

        >>> from sage.all import *
        >>> python.eval('a=5\nb=7\na+b', globals())
        12
        ''
        >>> b
        7

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

    Sage

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

    Python

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