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

# PythonContext -- persistent Python execution environment

- Usage:
    `new PythonContext`
    `PythonContext s`
    `ctx s`
- Inputs:
  - ctx, a Python context,
  - s, a string,
- Outputs:
  - a Python context,

## 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

- PythonContext _ String -- get value of variable in a python context
- listSymbols(PythonContext) -- get a table of all the variables and their values in a python context
- use(PythonContext) -- install variables from a python context

## Methods that use a Python context:

- listSymbols(PythonContext) -- get a table of all the variables and their values in a python context
- `new PythonContext`
- `new PythonContext from String`
- `PythonContext String`
- PythonContext _ String -- get value of variable in a python context
- use(PythonContext) -- install variables from 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 /build/macaulay2-88fgJW/macaulay2-1.25.11+ds/M2/Macaulay2/packages/Python/doc/context.m2:47:0.