Macaulay2 » Documentation
Packages » Python » PythonContext
next | previous | forward | backward | up | index | toc

PythonContext -- persistent Python execution environment

Description

The class PythonContext represents a persistent Python execution environment that maintains its own global namespace. It allows you to evaluate Python expressions and statements across multiple calls, preserving defined variables and imports.

When a PythonContext object is created, the given string is executed as Python code within a new global context. Subsequent calls evaluate additional Python code in the same context, allowing variables and imports to persist.

Each evaluation returns a PythonObject representing the result of the final expression in the string, if any.

i1 : math = PythonContext "from math import *"

o1 = math

o1 : PythonContext
i2 : math "x = sin(3.4)"
i3 : math "sin(3.4)"

o3 = -0.2555411020268312

o3 : PythonObject of class float
i4 : math "x"

o4 = -0.2555411020268312

o4 : PythonObject of class float
i5 : math "e"

o5 = 2.718281828459045

o5 : PythonObject of class float

Here, the import from the Python math module is performed once during initialization. The variable x remains available in subsequent calls to the same PythonContext instance.

Menu

Methods that use a Python context:

For the programmer

The object PythonContext is a self initializing type, with ancestor classes MutableHashTable < HashTable < Thing.


The source of this document is in Python/doc/context.m2:47:0.