modelx.cached#
- cached(space=None, name=None, is_cached=None, *funcs)#
Decorator to create or update a cells from a Python function.
Note
cached()
is an alies fordefcells()
.This convenience function serves as a decorator to create a new cells or update the formula of an existing cells directly from a Python function definition. It replaces the need to manually call
new_cells()
orset_formula()
on the parent space, or to set theformula
property.Examples
1. As a decorator without arguments
The code below creates a cells named
foo
in the current space. Iffoo
already exists in the current space, updates its formula.If the current space does not exist, a new space is created. If the current model does not exist, a new model is also created:
>>> import modelx as mx >>> @mx.defcells ... def foo(x): ... return x >>> foo <Cells Model1.Space1.foo(x)>
If a cells with the same name already exists in the current space, its formula is updated based on the decorated function:
>>> bar = foo >>> @mx.defcells ... def foo(x): ... return 2 * x >>> foo is bar True
2. As a decorator with arguments
The code below creates an uncached cells in a specified space with the specified name, “bar”. If the cells named “bar” already exists in the specified space, update its formula and
is_cached
property:>>> space = mx.new_space("Foo") >>> @mx.defcells(space=space, name='bar', is_cached=False) ... def foo(x): ... return x >>> foo <Cells Model1.Foo.bar(x)> >>> foo.is_cached False
3. As a function
Creates multiple cells from multiple function definitions:
def foo(x): return x def bar(y): return foo(y) foo, bar = defcells(foo, bar)
- Parameters:
space (optional) – For usage 2, specifies the space to create the cells in. Defaults to the current space of the current model.
name (optional) – For usage 2, specifies the name of the created cells. Defaults to the function name.
is_cached (optional) – For usage 2, a boolean indicating whether the cells should be cached. Defaults to
True
when creating a new cell andFalse
when updating an existing cell.*funcs – For usage 3, function objects. (
space
andname
can also accept function objects for this usage.)
- Returns:
For usage 1 and 2, the newly created single cells is returned. For usage 3, a list of newly created cells is returned.
See also
Changed in version 0.27.0::
cached()
is introduced as an alies.Changed in version 0.27.0:: The
is_cached
parameter is introduced.Changed in version 0.1.0: If the current space does not exist, a new space is created. If the current model does not exist, a new model is created.
Changed in version 0.1.0: If a cells with the same name already exists in the current space, its formula is updated based on the decorated function.