1 """An Python re-implementation of hierarchical module import.
3 This code is intended to be read, not executed. However, it does work
4 -- all you need to do to enable it is "import knee".
6 (The name is a pun on the klunkier predecessor of this module, "ni".)
10 import sys
, imp
, __builtin__
13 # Replacement for __import__()
14 def import_hook(name
, globals=None, locals=None, fromlist
=None):
15 parent
= determine_parent(globals)
16 q
, tail
= find_head_package(parent
, name
)
17 m
= load_tail(q
, tail
)
20 if hasattr(m
, "__path__"):
21 ensure_fromlist(m
, fromlist
)
24 def determine_parent(globals):
25 if not globals or not globals.has_key("__name__"):
27 pname
= globals['__name__']
28 if globals.has_key("__path__"):
29 parent
= sys
.modules
[pname
]
30 assert globals is parent
.__dict
__
35 parent
= sys
.modules
[pname
]
36 assert parent
.__name
__ == pname
40 def find_head_package(parent
, name
):
49 qname
= "%s.%s" % (parent
.__name
__, head
)
52 q
= import_module(head
, qname
, parent
)
57 q
= import_module(head
, qname
, parent
)
59 raise ImportError, "No module named " + qname
61 def load_tail(q
, tail
):
65 if i
< 0: i
= len(tail
)
66 head
, tail
= tail
[:i
], tail
[i
+1:]
67 mname
= "%s.%s" % (m
.__name
__, head
)
68 m
= import_module(head
, mname
, m
)
70 raise ImportError, "No module named " + mname
73 def ensure_fromlist(m
, fromlist
, recursive
=0):
79 except AttributeError:
82 ensure_fromlist(m
, all
, 1)
84 if sub
!= "*" and not hasattr(m
, sub
):
85 subname
= "%s.%s" % (m
.__name
__, sub
)
86 submod
= import_module(sub
, subname
, m
)
88 raise ImportError, "No module named " + subname
90 def import_module(partname
, fqname
, parent
):
92 return sys
.modules
[fqname
]
96 fp
, pathname
, stuff
= imp
.find_module(partname
,
97 parent
and parent
.__path
__)
101 m
= imp
.load_module(fqname
, fp
, pathname
, stuff
)
105 setattr(parent
, partname
, m
)
109 # Replacement for reload()
110 def reload_hook(module
):
111 name
= module
.__name
__
113 return import_module(name
, name
, None)
116 parent
= sys
.modules
[pname
]
117 return import_module(name
[i
+1:], name
, parent
)
120 # Save the original hooks
121 original_import
= __builtin__
.__import
__
122 original_reload
= __builtin__
.reload
124 # Now install our hooks
125 __builtin__
.__import
__ = import_hook
126 __builtin__
.reload = reload_hook