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)
<class 'sage.misc.lazy_import.LazyImport'>
sage: ZZ(4.0)
4

AUTHOR:

  • Robert Bradshaw
class sage.misc.lazy_import.LazyImport(module, name)

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)
...
TypeError: no conversion of this rational to integer
sage.misc.lazy_import.lazy_import(module, names, _as=None)

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.

EXAMPLES:

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

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

Previous topic

Lazy format strings

Next topic

Logging of Sage sessions.

This Page