UserSpace.new_module#

UserSpace.new_module(name, path, module)#

Assigns a user module to a Reference associating a new ModuleData object

This module assigns a module module to a Reference name. module can either be a path to the module file or a module object. In case a module is passed, the source code of the module needs to be retrievable. The source code of the module is then saved as the file specified by path when the model is saved. A new ModuleData object is created and inserted to the module as _mx_dataclient attribute. The module associted by this method is not registered in sys.modules, unless it has been registered beforehand. When the containing model is read back, the module’s name is set to <unnamed module>.

This method should not be used for modules in the Python standard library or third party packages registered in sys.modules, such as math, numpy and pandas. For such module, the normal assignment operation should be used, e.g. space.np = np.

Example

Suppose the following code is saved in “sample.py” in the current directory.

def triple(x)
    return 3 * x

The code below creates a Reference named “foo” in space:

>>> space.new_module("foo", "modules/sample.py", "sample.py")

The module becomes accessible as foo in space:

>>> space.foo
<module 'sample' from 'C:\path\to\samplemodule.py'>

>>> @mx.defcells(space)
... def bar(y):
        return foo.triple(y)

>>> space.foo.bar(3)
9

Let model be the ultimate parent model of space. The next code creates a directory named “model” under the current directory, and within the “model” directory, the module is saved as “sample.py” in the “modules” sub-directory of the “model” dir, as specified by the path paramter to this method.

>>> model.write("model")
Parameters:
  • name (str) – Name of the Reference

  • path – A path to a file to save the module. If a relative path is given, it is relative to the model folder.

  • module – A path to a module file as a string or path-like object, or a module object.

New in version 0.13.0.

See also