Module mpython.utils
Classes
class DelayedImport
-
Expand source code
class DelayedImport: """A utility to delay the import of modules or variables. Until they are imported, import paths are wrapped in a `DelayedImportElement` object. The first time an element is accessed, it triggers the underlying import and assign the imported module or object into the `DelayedImport` child class, while getting rid of the `DelayedImportElement` wrapper. Thereby, the next time the element is accessed, the module is directly obtained. This strategy minimizes overhead on subsequent calls (no need to test whether the module has already been imported or not). Example ------- ```python # module_with_definitions.py class _imports(DelayedImport): Array = 'mpython.array.Array' Cell = 'mpython.cell.Cell' def foo(): Array = _imports.Array Cell = _imports.Cell ``` """ def __init_subclass__(cls): for key, val in cls.__dict__.items(): if key.startswith("__"): continue setattr(cls, key, DelayedImportElement(key, val))
A utility to delay the import of modules or variables.
Until they are imported, import paths are wrapped in a
DelayedImportElement
object. The first time an element is accessed, it triggers the underlying import and assign the imported module or object into theDelayedImport
child class, while getting rid of theDelayedImportElement
wrapper. Thereby, the next time the element is accessed, the module is directly obtained. This strategy minimizes overhead on subsequent calls (no need to test whether the module has already been imported or not).Example
# module_with_definitions.py class _imports(DelayedImport): Array = 'mpython.array.Array' Cell = 'mpython.cell.Cell' def foo(): Array = _imports.Array Cell = _imports.Cell
Subclasses
- mpython.array._imports
- mpython.core.base_types._imports
- mpython.core.delayed_types._imports
- mpython.core.mixin_types._imports
- mpython.core.wrapped_types._imports
- mpython.struct._imports
class DelayedImportElement (name, import_path=None)
-
Expand source code
def __get__(self, instance, owner): assert instance is None imported = self._import() setattr(owner, self.name, imported) return imported