Environment API Reference
Environment
Environment for managing model variables and their relationships.
An Environment is a container that manages all variables created by the user. It ensures that variables used together come from the same environment and maintains consistency across multiple expressions.
Environments serve as context managers to automatically manage variable scoping.
Attributes:
-
num_variables(int) –The number of variables registered in this environment.
-
id(int) –Unique identifier for this environment.
Examples:
Use as a context manager:
>>> from luna_model import Environment, Variable
>>> with Environment() as env:
... x = Variable("x", env=env)
... y = Variable("y", env=env)
Create and manage explicitly:
>>> env = Environment()
>>> x = Variable("x", env=env)
>>> print(env.num_variables) # 1
1
>>> var = env.get_variable("x")
Notes
Variables from different environments cannot be combined in the same expression or constraint. This prevents accidental mixing of unrelated models.
num_variables: int
property
id: int
property
__init__() -> None
Initialize a new environment.
__enter__() -> Environment
Enter the environment context.
__exit__(exc_type, exc_value, exc_traceback) -> None
Exit the environment context.
get_variable(name: str) -> Variable
variables() -> list[Variable]
equal_contents(other: Environment) -> bool
Check if two environments have equal content.
Parameters:
-
other(Environment) –The environment to compare with.
Returns:
-
bool–True if environments have the same variables.
encode() -> bytes
Serialize the environment into a compact binary format.
Returns:
-
bytes–Encoded environment representation.
serialize() -> bytes
Serialize the environment into a compact binary format.
This is an alias for :meth:encode.
Returns:
-
bytes–Encoded environment representation.
decode(data: bytes) -> Environment
classmethod
Reconstruct an environment from encoded bytes.
Parameters:
-
data(bytes) –Binary blob returned by :meth:
encodeor :meth:serialize.
Returns:
-
Environment–Deserialized environment object.
Raises:
-
DecodingError–If decoding fails due to corruption or incompatibility.
Examples:
deserialize(data: bytes) -> Environment
classmethod
__reduce__() -> tuple[Callable[[bytes], Environment], tuple[bytes]]
Support for pickle serialization.
Returns:
-
tuple–A tuple of (decoder_function, encoded_data) for pickle.
Notes
This method is called automatically by Python's pickle module.
__eq__(other: Environment) -> bool
Check if two environments are exactly equal.
__contains__(var: str) -> bool
__str__() -> str
Environment as a string.