1
2
3
4
5 """ Helper to enable simple lazy module import.
6
7 'Lazy' means the actual import is deferred until an attribute is
8 requested from the module's namespace. This has the advantage of
9 allowing all imports to be done at the top of a script (in a
10 prominent and visible place) without having a great impact
11 on startup time.
12
13 Copyright (c) 1999-2005, Marc-Andre Lemburg; mailto:mal@lemburg.com
14 See the documentation for further information on copyrights,
15 or contact the author. All Rights Reserved.
16 """
17
18
19
20 _debug = 0
21
22
23
25
26 """ Lazy module class.
27
28 Lazy modules are imported into the given namespaces whenever a
29 non-special attribute (there are some attributes like __doc__
30 that class instances handle without calling __getattr__) is
31 requested. The module is then registered under the given name
32 in locals usually replacing the import wrapper instance. The
33 import itself is done using globals as global namespace.
34
35 Example of creating a lazy load module:
36
37 ISO = LazyModule('ISO',locals(),globals())
38
39 Later, requesting an attribute from ISO will load the module
40 automatically into the locals() namespace, overriding the
41 LazyModule instance:
42
43 t = ISO.Week(1998,1,1)
44
45 """
46
47 __lazymodule_init = 0
48
49
50 __lazymodule_name = ''
51
52
53 __lazymodule_loaded = 0
54
55
56 __lazymodule_locals = None
57
58
59 __lazymodule_globals = None
60
61 - def __init__(self, name, locals, globals=None):
62
63 """ Create a LazyModule instance wrapping module name.
64
65 The module will later on be registered in locals under the
66 given module name.
67
68 globals is optional and defaults to locals.
69
70 """
71 self.__lazymodule_locals = locals
72 if globals is None:
73 globals = locals
74 self.__lazymodule_globals = globals
75 mainname = globals.get('__name__', '')
76 if mainname:
77 self.__name__ = mainname + '.' + name
78 self.__lazymodule_name = name
79 else:
80 self.__name__ = self.__lazymodule_name = name
81 self.__lazymodule_init = 1
82
110
112
113 """ Import the module on demand and get the attribute.
114 """
115 if self.__lazymodule_loaded:
116 raise AttributeError, name
117 if _debug:
118 print 'LazyModule: ' \
119 'Module load triggered by attribute %r read access' % name
120 module = self.__lazymodule_import()
121 return getattr(module, name)
122
139
141 return "<LazyModule '%s'>" % self.__name__
142