469,602 Members | 1,927 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,602 developers. It's quick & easy.

import hooks

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:]:
tempmod = getattr(tempmod, part)
= tempmod
except AttributeError:

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

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

PS. pleace CC me directly
Jul 18 '05 #1
0 874

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Petri Savolainen | last post: by
reply views Thread by Gonçalo Rodrigues | last post: by
4 posts views Thread by Matt Whiteley | last post: by
8 posts views Thread by Grant D. Watson | last post: by
reply views Thread by Mustafa Thamer | last post: by
43 posts views Thread by Dan Perl | last post: by
reply views Thread by Carlos Ribeiro | last post: by
5 posts views Thread by Steve Holden | last post: by
23 posts views Thread by Shane Hathaway | last post: by
reply views Thread by | last post: by
reply views Thread by suresh191 | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.