dantro._import_tools module

Tools for module importing, e.g. lazy imports.

dantro._import_tools.get_from_module(mod, *, name: str)[source]

Retrieves an attribute from a module, if necessary traversing along the module string.

Parameters
  • mod – Module to start looking at

  • name (str) – The .-separated module string leading to the desired object.

dantro._import_tools.import_module_or_object(module: str = None, name: str = None)[source]

Imports a module or an object using the specified module string and the object name.

Parameters
  • module (str, optional) – A module string, e.g. numpy.random. If this is not given, it will import from the :py:mod`builtins` module. Also, relative module strings are resolved from dantro.

  • name (str, optional) – The name of the object to retrieve from the chosen module and return. This may also be a dot-separated sequence of attribute names which can be used to traverse along attributes.

Returns

The chosen module or object, i.e. the object found at <module>.<name>

Raises

AttributeError – In cases where part of the name argument could not be resolved due to a bad attribute name.

class dantro._import_tools.LazyLoader(mod_name: str, *, _depth: int = 0)[source]

Bases: object

Delays import until the module’s attributes are accessed.

This is inspired by the implementation by Dboy Liao:

https://levelup.gitconnected.com/python-trick-lazy-module-loading-df9b9dc111af

It extends on it by allowing a depth until which loading will be lazy.

__init__(mod_name: str, *, _depth: int = 0)[source]

Initialize a placeholder for a module.

Warning

Values of _depth > 0 may lead to unexpected behaviour of the root module, i.e. this object, because attribute calls do not yield an actual object. Only use this in scenarios where you are in full control over the attribute calls.

We furthermore suggest to not make the LazyLoader instance publicly available in such cases.

Parameters
  • mod_name (str) – The module name to lazy-load upon attribute call.

  • _depth (int, optional) – With a depth larger than zero, attribute calls are not leading to an import yet, but to the creation of another LazyLoader instance (with depth reduced by one). Note the warning above regarding usage.

resolve()[source]