Model.new_macro#
- Model.new_macro(name=None, formula=None)[source]#
Create a new
Macroin this model.Creates a macro that acts as a callable Python function saved within the model. Macros share a dedicated global namespace that includes the model itself as both
mx_modeland by the model’s name.- Parameters:
name (str, optional) – Name for the macro. If omitted and a function is provided, the function’s name is used. If the function name is not valid for a macro name, an error is raised. Must be a valid Python identifier, and must not start with an underscore.
formula (callable, optional) –
The function definition. Can be:
A Python function (def or lambda)
None to create an empty macro (not recommended)
- Returns:
The newly created macro object
- Return type:
Example
Creating a macro using new_macro:
>>> model = mx.new_model('MyModel') >>> def get_model_info(): ... return f"Model: {mx_model._name}" >>> model.new_macro(formula=get_model_info) <Macro MyModel.get_model_info> >>> model.get_model_info() 'Model: MyModel'
Above is equivalent to creating a macro using the decorator:
>>> @mx.defmacro ... def get_model_info(): ... return f"Model: {mx_model._name}" <Macro MyModel.get_model_info>
Creating a macro with a custom name from a lambda function:
>>> model.new_macro('double', lambda x: x * 2) <Macro MyModel.double> >>> model.double(5) 10
Macros can call other macros in the same model:
>>> @mx.defmacro ... def helper(): ... return 42 >>> @mx.defmacro ... def main(): ... return helper() * 2 >>> model.main() 84
See also
defmacro(): Decorator to create macrosmacros: Access all macrosexport(): Export model with macros
Added in version 0.30.0.