Macro#
- class Macro(_impl)[source]#
A callable Python function that can be saved within a Model.
Macros are Python functions stored in a model that can be used to manipulate and interact with the model. All macros in a model share a dedicated global namespace that includes the model itself as both
mx_modeland by the model’s name.- Creation:
Macros can be created using the
defmacro()decorator:>>> import modelx as mx >>> m = mx.new_model('MyModel') >>> @mx.defmacro ... def get_model_name(): ... return mx_model._name >>> @mx.defmacro(model=m, name='print_name') ... def print_model_name(message): ... print(f"{message} {get_model_name()}")
- Execution:
Macros are executed by calling them as model attributes:
>>> m.get_model_name() 'MyModel' >>> m.print_name("This model is") This model is MyModel
- Listing Macros:
Access all macros through the model’s
macrosproperty:>>> m.macros {'get_model_name': <Macro MyModel.get_model_name>, 'print_name': <Macro MyModel.print_name>}
- Export:
When a model is exported, macros are saved in
_mx_macros.pyas regular Python functions, allowing them to work with both modelx models and exported models.
See also
defmacro(): Decorator to create macrosmacros: Access model’s macrosexport(): Export model as Python package
Added in version 0.30.0.