Lazy imports

This module allows one to lazily import callable objects into the global namespace, where the actual import is delayed until the object is actually called or inspected. This is useful for modules that are expensive to import or may cause circular references, though there is some overhead in its use.

EXAMPLES:

sage: from sage.misc.lazy_import import lazy_import
sage: lazy_import('sage.rings.all', 'ZZ')
sage: type(ZZ)
<type 'sage.misc.lazy_import.LazyImport'>
sage: ZZ(4.0)
4

AUTHOR:

  • Robert Bradshaw
class sage.misc.lazy_import.LazyImport

Bases: object

EXAMPLES:

sage: from sage.misc.lazy_import import LazyImport
sage: my_integer = LazyImport('sage.rings.all', 'Integer')
sage: my_integer(4)
4
sage: my_integer('101', base=2)
5
sage: my_integer(3/2)
Traceback (most recent call last):
...
TypeError: no conversion of this rational to integer
sage.misc.lazy_import.get_star_imports(module_name)

Lookup the list of names in a module that would be imported with “import *” either via a cache or actually importing.

EXAMPLES:

sage: from sage.misc.lazy_import import get_star_imports
sage: 'get_star_imports' in get_star_imports('sage.misc.lazy_import')
True
sage: 'EllipticCurve' in get_star_imports('sage.schemes.all')
True
sage.misc.lazy_import.lazy_import(module, names, _as=None, namespace=None, overwrite=True)

Create a lazy import object and inject it into the caller’s global namespace. For the purposes of introspection and calling, this like performing a lazy “from module import name” where the import is delayed until the object actually is used or inspected.

INPUT:

  • module: a string representing the module to import.
  • names: a string or list of strings representing the names to import from module.
  • _as: (optional) a string or list of strings representing the aliases of the names imported.
  • namespace: The namespace where importing the names. By default, import the names to current namespace.
  • overwrite: (default: True) If set to True and a name is already in the namespace, overwrite it with the lazy_import-ed name.

EXAMPLES:

sage: from sage.misc.lazy_import import lazy_import
sage: lazy_import('sage.rings.all', 'ZZ')
sage: type(ZZ)
<type 'sage.misc.lazy_import.LazyImport'>
sage: ZZ(4.0)
4
sage: lazy_import('sage.rings.all', 'RDF', 'my_RDF')
sage: my_RDF._get_object() is RDF
True
sage: my_RDF(1/2)
0.5

sage: lazy_import('sage.all', ['QQ', 'RR'], ['my_QQ', 'my_RR'])
sage: my_QQ._get_object() is QQ
True
sage: my_RR._get_object() is RR
True

Upon the first use, the object is injected directly into the calling namespace:

sage: lazy_import('sage.all', 'ZZ', 'my_ZZ')
sage: my_ZZ is ZZ
False
sage: my_ZZ(37)
37
sage: my_ZZ is ZZ
True
sage.misc.lazy_import.save_cache_file()

Used to save the cached * import names.

TESTS:

sage: import sage.misc.lazy_import
sage: sage.misc.lazy_import.save_cache_file()

Previous topic

Lazy format strings

Next topic

Logging of Sage sessions.

This Page