import hooks

S

Simon Dahlbacka

I recently had a problem caused by path extension (sys.path.extend) so
that a module/package got imported twice both as foo.module and
module, which caused all sorts of problems.

Naturally best is to use absolute paths and avoid path extension, but
this cannot be done in all places.

Anyway, I'd like to prevent such things from happening again by
inserting an __import__ hook to catch these kinds of problems.

I got it installed alright, and it works in the sense that importing
works, but it does not notice double imports. So how exactly am I to
test for this case?

I thought that if __file__ for two modules are the same but not
id(module) would work, but apparently not?

a somewhat related question: why does not built in modules have a
__file__ attribute?

my attempt:
__moduleCache = {}

def __importhook__(name, _globals=None, _locals=None, fromlist=None):
"""Sanity check module imports so that we do not get the same
problem with
doubly imported modules again"""

mod = _orig__import__(name, globals, locals, fromlist)

tempmod = mod
components = name.split(".")
for part in components[1:]:
try:
tempmod = getattr(tempmod, part)
__moduleCache[".".join(components[components.index(part):])]
= tempmod
except AttributeError:
pass

for modname in __moduleCache:
if name in sys.builtin_module_names:
break
if modname in sys.builtin_module_names:
continue

if (getattr(mod, "__file__") ==
getattr(__moduleCache[modname], "__file__") and
id(mod) != id(__moduleCache[modname])):
assert False
return mod


/Simon

PS. pleace CC me directly
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top