2 :mod:`imputil` --- Import utilities
3 =====================================================
6 :synopsis: Manage and augment the import process.
10 The :mod:`imputil` module has been removed in Python 3.0.
13 .. index:: statement: import
15 This module provides a very handy and useful mechanism for custom
16 :keyword:`import` hooks. Compared to the older :mod:`ihooks` module,
17 :mod:`imputil` takes a dramatically simpler and more straight-forward
18 approach to custom :keyword:`import` functions.
21 .. class:: ImportManager([fs_imp])
23 Manage the import process.
25 .. method:: ImportManager.install([namespace])
27 Install this ImportManager into the specified namespace.
29 .. method:: ImportManager.uninstall()
31 Restore the previous import mechanism.
33 .. method:: ImportManager.add_suffix(suffix, importFunc)
40 Base class for replacing standard import functions.
42 .. method:: Importer.import_top(name)
44 Import a top-level module.
46 .. method:: Importer.get_code(parent, modname, fqname)
48 Find and retrieve the code for the given module.
50 *parent* specifies a parent module to define a context for importing.
51 It may be ``None``, indicating no particular context for the search.
53 *modname* specifies a single module (not dotted) within the parent.
55 *fqname* specifies the fully-qualified module name. This is a
56 (potentially) dotted name from the "root" of the module namespace
59 If there is no parent, then modname==fqname.
61 This method should return ``None``, or a 3-tuple.
63 * If the module was not found, then ``None`` should be returned.
65 * The first item of the 2- or 3-tuple should be the integer 0 or 1,
66 specifying whether the module that was found is a package or not.
68 * The second item is the code object for the module (it will be
69 executed within the new module's namespace). This item can also
70 be a fully-loaded module object (e.g. loaded from a shared lib).
72 * The third item is a dictionary of name/value pairs that will be
73 inserted into new module before the code object is executed. This
74 is provided in case the module's code expects certain values (such
75 as where the module was found). When the second item is a module
76 object, then these names/values will be inserted *after* the module
77 has been loaded/initialized.
80 .. class:: BuiltinImporter()
82 Emulate the import mechanism for built-in and frozen modules. This is a
83 sub-class of the :class:`Importer` class.
85 .. method:: BuiltinImporter.get_code(parent, modname, fqname)
89 .. function:: py_suffix_importer(filename, finfo, fqname)
93 .. class:: DynLoadSuffixImporter([desc])
97 .. method:: DynLoadSuffixImporter.import_file(filename, finfo, fqname)
101 .. _examples-imputil:
106 This is a re-implementation of hierarchical module import.
108 This code is intended to be read, not executed. However, it does work
109 -- all you need to do to enable it is "import knee".
111 (The name is a pun on the clunkier predecessor of this module, "ni".)
115 import sys, imp, __builtin__
117 # Replacement for __import__()
118 def import_hook(name, globals=None, locals=None, fromlist=None):
119 parent = determine_parent(globals)
120 q, tail = find_head_package(parent, name)
121 m = load_tail(q, tail)
124 if hasattr(m, "__path__"):
125 ensure_fromlist(m, fromlist)
128 def determine_parent(globals):
129 if not globals or not globals.has_key("__name__"):
131 pname = globals['__name__']
132 if globals.has_key("__path__"):
133 parent = sys.modules[pname]
134 assert globals is parent.__dict__
139 parent = sys.modules[pname]
140 assert parent.__name__ == pname
144 def find_head_package(parent, name):
153 qname = "%s.%s" % (parent.__name__, head)
156 q = import_module(head, qname, parent)
161 q = import_module(head, qname, parent)
163 raise ImportError("No module named " + qname)
165 def load_tail(q, tail):
169 if i < 0: i = len(tail)
170 head, tail = tail[:i], tail[i+1:]
171 mname = "%s.%s" % (m.__name__, head)
172 m = import_module(head, mname, m)
174 raise ImportError("No module named " + mname)
177 def ensure_fromlist(m, fromlist, recursive=0):
183 except AttributeError:
186 ensure_fromlist(m, all, 1)
188 if sub != "*" and not hasattr(m, sub):
189 subname = "%s.%s" % (m.__name__, sub)
190 submod = import_module(sub, subname, m)
192 raise ImportError("No module named " + subname)
194 def import_module(partname, fqname, parent):
196 return sys.modules[fqname]
200 fp, pathname, stuff = imp.find_module(partname,
201 parent and parent.__path__)
205 m = imp.load_module(fqname, fp, pathname, stuff)
209 setattr(parent, partname, m)
213 # Replacement for reload()
214 def reload_hook(module):
215 name = module.__name__
217 return import_module(name, name, None)
220 parent = sys.modules[pname]
221 return import_module(name[i+1:], name, parent)
224 # Save the original hooks
225 original_import = __builtin__.__import__
226 original_reload = __builtin__.reload
228 # Now install our hooks
229 __builtin__.__import__ = import_hook
230 __builtin__.reload = reload_hook
235 Also see the :mod:`importers` module (which can be found
236 in :file:`Demo/imputil/` in the Python source distribution) for additional