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
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
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
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:
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
We check that lazy_import() also works for methods:
sage: class Foo(object):
... lazy_import('sage.all', 'plot')
sage: class Bar(Foo):
... pass
sage: type(Foo.__dict__['plot'])
<type 'sage.misc.lazy_import.LazyImport'>
sage: 'EXAMPLES' in Bar.plot.__doc__
True
sage: type(Foo.__dict__['plot'])
<type 'function'>
Used to save the cached * import names.
TESTS:
sage: import sage.misc.lazy_import
sage: sage.misc.lazy_import.save_cache_file()