pygx.coding¶
Runtime compilation, execution and sandboxing of Python source code.
coding
¶
Runtime compilation, execution and sandboxing of Python source code.
pygx.coding provides a small toolkit for compiling and executing Python
source code at runtime under controlled conditions. It is used internally by
PyGX to materialize generated programs, but is exposed as a public sub-package
because the building blocks are useful on their own:
parse/evaluate/runfor compiling and executing Python source.make_functionfor synthesizing a callable from a source string.permission/get_permissionfor declaring which language features (assignment, function definition, import) the executed source may use.sandbox_call/maybe_sandbox_callfor executing a callable in a child process with a timeout.CodeError/SerializationErrorfor errors raised by the above APIs.
NO_TYPE_ANNOTATION
module-attribute
¶
Sentinel for make_function's return_type meaning "no annotation".
CodeError
¶
Bases: RuntimeError
Error raised when Python code fails to parse or execute.
Wraps the original exception (cause) together with the source code
(code) and, when determinable, the 1-based line range of the offending
code (lineno / end_lineno, None otherwise).
Source code in pygx/coding/_errors.py
code_lines
¶
Returns the code lines from start_line (0-based) to end_line.
format
¶
Formats the error, optionally with the complete source appended.
Source code in pygx/coding/_errors.py
SerializationError
¶
Bases: RuntimeError
Error raised when a value cannot be serialized or deserialized.
Raised by the sandboxed-execution APIs when a payload or result cannot
cross the process boundary. Wraps the original exception as cause.
Source code in pygx/coding/_errors.py
CodePermission
¶
Bases: Flag
Flags for language constructs permitted during code execution.
Flags can be combined with |. Two combinations are predefined:
CodePermission.BASIC (ASSIGN | CALL) and CodePermission.ALL.
ASSIGN
class-attribute
instance-attribute
¶
Allows assignment statements — plain (x = y), augmented
(x += y) and annotated (x: int = y).
CONDITION
class-attribute
instance-attribute
¶
Allows if and match statements.
LOOP
class-attribute
instance-attribute
¶
Allows for / while loops, plus with / async for /
async with blocks.
EXCEPTION
class-attribute
instance-attribute
¶
Allows try, raise and assert statements.
CLASS_DEFINITION
class-attribute
instance-attribute
¶
Allows class definitions.
FUNCTION_DEFINITION
class-attribute
instance-attribute
¶
Allows def / lambda definitions (and return / yield).
IMPORT
class-attribute
instance-attribute
¶
Allows import and from ... import statements.
context
¶
Context manager to inject symbols for code execution.
Symbols injected here become part of the globals for pg.coding.evaluate
and pg.coding.run calls made within the scope. Nested scopes add to
(and may override) symbols from outer scopes.
Example:
Source code in pygx/coding/_execution.py
evaluate
¶
evaluate(
code: str,
*,
global_vars: dict[str, Any] | None = None,
permission: CodePermission | None = None,
returns_stdout: bool = False,
outputs_intermediate: bool = False
) -> Any | dict[str, Any]
Executes Python code in the current process.
The code is parsed and validated against permission before execution,
which limits the language constructs (assignment, loops, imports, etc.)
the code may use. Note that permission control is not a security boundary:
the code still runs with full access to the current process. Use
pg.coding.run with sandbox=True to execute in a child process.
Example:
Intermediate variables can be exposed as well:
assert pg.coding.evaluate(
'x = 1\nx + 2', outputs_intermediate=True
) == {'x': 1, '__result__': 3, '__stdout__': ''}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Python code to run. |
required |
global_vars
|
dict[str, Any] | None
|
An optional dict as the globals that could be referenced by
the code, merged over the symbols injected via |
None
|
permission
|
CodePermission | None
|
Permission for the Python code to run. If None, the
permission from the current |
None
|
returns_stdout
|
bool
|
If True, the captured stdout (a str) will be returned. |
False
|
outputs_intermediate
|
bool
|
Applicable when returns_stdout is False. If True, a dict will be returned containing the variables defined or updated by the code, with the last statement's value accessible by key 'result' and the captured stdout accessible by key 'stdout'. Otherwise the value of the last statement will be returned. |
False
|
Returns:
| Type | Description |
|---|---|
Any | dict[str, Any]
|
The value of the last statement of the code block if it is an |
Any | dict[str, Any]
|
expression or an assignment (the assigned value); otherwise the value |
Any | dict[str, Any]
|
of the last defined variable. Or the dict of intermediate variables |
Any | dict[str, Any]
|
described under |
Any | dict[str, Any]
|
str when |
Any | dict[str, Any]
|
defines no variable at all and does not end in an expression, "the |
Any | dict[str, Any]
|
last defined variable" falls back to the last symbol in the |
Any | dict[str, Any]
|
execution globals — which can be a value injected via |
Any | dict[str, Any]
|
|
Any | dict[str, Any]
|
produced. End the code with an expression to make the result |
Any | dict[str, Any]
|
explicit. |
Raises:
| Type | Description |
|---|---|
CodeError
|
If the code fails to parse, uses a construct not granted by
|
Source code in pygx/coding/_execution.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
get_context
¶
Gets the symbols injected by the current pg.coding.context scope.
maybe_sandbox_call
¶
maybe_sandbox_call(
func: Callable[..., Any],
*args: Any,
sandbox: bool | None = None,
timeout: float | None = None,
**kwargs: Any
) -> Any
Calls a function, optionally in a sandbox process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Function to call. |
required |
*args
|
Any
|
Positional args that will be passed to |
()
|
sandbox
|
bool | None
|
If True, calls |
None
|
timeout
|
float | None
|
Execution timeout in seconds. If None, waits for |
None
|
**kwargs
|
Any
|
Keyword args that will be passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The return value of |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If the execution time exceeds the timeout. |
Exception
|
Exception raised from |
Source code in pygx/coding/_execution.py
run
¶
run(
code: str,
*,
global_vars: dict[str, Any] | None = None,
permission: CodePermission | None = None,
returns_stdout: bool = False,
outputs_intermediate: bool = False,
sandbox: bool | None = None,
timeout: float | None = None
) -> Any | dict[str, Any]
Executes Python code, optionally in a sandbox process.
Same as pg.coding.evaluate, with the option to execute the code in a
child process (sandbox) and to bound its execution time (timeout).
Example:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Python code to run. |
required |
global_vars
|
dict[str, Any] | None
|
An optional dict as the globals that could be referenced by
the code, merged over the symbols injected via |
None
|
permission
|
CodePermission | None
|
Permission for the Python code to run. If None, the
permission from the current |
None
|
returns_stdout
|
bool
|
If True, the captured stdout (a str) will be returned. |
False
|
outputs_intermediate
|
bool
|
Applicable when returns_stdout is False. If True, a dict will be returned containing the variables defined or updated by the code, with the last statement's value accessible by key 'result' and the captured stdout accessible by key 'stdout'. Otherwise the value of the last statement will be returned. |
False
|
sandbox
|
bool | None
|
If True, run code in a child process; if False, run code in the current process. If None, try the child process first and fall back to the current process when the code (or its result) cannot be serialized across the process boundary. |
None
|
timeout
|
float | None
|
Execution timeout in seconds. If None, waits for the code to complete. |
None
|
Returns:
| Type | Description |
|---|---|
Any | dict[str, Any]
|
The value of the last statement of the code block, the dict of |
Any | dict[str, Any]
|
intermediate variables, or the captured stdout — see |
Any | dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
CodeError
|
If the code fails to parse, uses a construct not granted by
|
TimeoutError
|
If the execution time exceeds the timeout. |
Source code in pygx/coding/_execution.py
sandbox_call
¶
sandbox_call(
func: Callable[..., Any],
*args: Any,
timeout: float | None = None,
**kwargs: Any
) -> Any
Calls a function in a child process, with an optional timeout.
The function, its arguments and its return value are shipped between the
parent and the child process via pickling (falling back to the optional
cloudpickle for lambdas, closures and locally-defined callables). On
timeout, the child process is killed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Function to call. |
required |
*args
|
Any
|
Positional arguments for |
()
|
timeout
|
float | None
|
Execution timeout in seconds. If None, waits for |
None
|
**kwargs
|
Any
|
Keyword arguments for |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Return value from |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If the execution time exceeds the timeout. |
SerializationError
|
If |
Exception
|
Exception raised from |
Source code in pygx/coding/_execution.py
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
make_function
¶
make_function(
name: str,
args: list[str],
body: list[str | list],
*,
exec_globals: dict[str, Any] | None = None,
exec_locals: dict[str, Any] | None = None,
return_type: Any = NO_TYPE_ANNOTATION
)
Creates a function dynamically from source.
Example:
add = pg.coding.make_function(
'add',
args=['x: int', 'y: int'],
body=['return x + y'],
return_type=int,
)
assert add(1, 2) == 3
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The function name. |
required |
args
|
list[str]
|
The argument declarations, e.g. |
required |
body
|
list[str | list]
|
The source lines of the function body, without indentation. A
nested list is one indent level deeper, so a block reads as a block:
|
required |
exec_globals
|
dict[str, Any] | None
|
The globals available to the generated function. |
None
|
exec_locals
|
dict[str, Any] | None
|
Local symbols available to the function definition (e.g. types referenced by annotations). |
None
|
return_type
|
Any
|
The return type annotation of the function, or
|
NO_TYPE_ANNOTATION
|
The created function object is returned.
Source code in pygx/coding/_function_generation.py
parse
¶
parse(code: str, permission: CodePermission | None = None) -> Module
Parses Python source code, optionally enforcing a permission.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Python source code. |
required |
permission
|
CodePermission | None
|
If not None, the parsed AST is validated so that |
None
|
Returns:
| Type | Description |
|---|---|
Module
|
The parsed |
Raises:
| Type | Description |
|---|---|
CodeError
|
If |
Source code in pygx/coding/_parsing.py
get_permission
¶
get_permission() -> CodePermission | None
Gets the current permission for code execution.
Returns None when no pg.coding.permission context is active, in which
case code execution is unrestricted.
Source code in pygx/coding/_permissions.py
permission
¶
permission(perm: CodePermission) -> Iterator[CodePermission]
Context manager for controlling the permission for code execution.
When the permission context manager is nested, the outermost permission
will be used. This design allows users to control permission at the top
level.
Example:
with pg.coding.permission(pg.coding.CodePermission.BASIC):
assert pg.coding.evaluate('x = 1\nx + 1') == 2
# Raises `pg.coding.CodeError`: `import` is not allowed.
pg.coding.evaluate('import os')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
perm
|
CodePermission
|
Code execution permission. |
required |
Yields:
| Type | Description |
|---|---|
CodePermission
|
Actual permission applied. |
Source code in pygx/coding/_permissions.py
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2