2.3a1: importhooks oddity

Hans Nowak wurmy at earthlink.net
Thu Jan 2 20:46:08 CET 2003


[me]
>>Yes, this works... a whole slew of Wahey's. :-)  So it's not a bug, but this 
>>behavior is still a bit confusing, at least on Windows (as opposed to other 
>>platforms where it seems to work as expected). Is this the desired behavior? 

[JvR]
> Can you provide more details? Your original example showed that on 
> cygwin there was a fresh sys.path item (perhaps added by site.py or 
> after site.py was run) not yet "touched" by an import, and on Windows 
> there wasn't. You could compare sys.path with and without the -S ("no 
> site.py") option.

OK, updated code:

import sys

print '' in sys.path
print '' in sys.path_importer_cache.keys()

def f(path):
     print "Wahey!", `path`
     raise ImportError

sys.path_hooks.append(f)

import nothing

On Windows:

(P:\test\2.3) $ python test-importhooks-2.py
True
True
Traceback (most recent call last):
   File "test-importhooks-2.py", line 14, in ?
     import nothing  # needless to say, doesn't exist
ImportError: No module named nothing

On Cygwin:

(P:\test\2.3) $ c:\cygwin\usr\local\bin\python2.3.exe test-importhooks-2.py
True
False
Wahey! ''
Traceback (most recent call last):
   File "test-importhooks-2.py", line 14, in ?
     import nothing  # needless to say, doesn't exist
ImportError: No module named nothing

The empty string '' isn't a key in sys.path_importer_cache, apparently. 
(Interesting, when I run Cygwin-Python's interactive interpreter, and inspect 
sys.path_importer_cache, the empty string *is* there...)

When run with -S, both scripts produce a whole list of Wahey's, and the two 
conditions at the beginning are True and False, respectively.

>>If I understand correctly, then registering any function or class in
>>path_hooks is useless on Windows for path "", since it will be bypassed.
> 
> Not sure what you mean. I'd think you could still register a hook for "" 
> and make it do "something".

Hmm, well, I mean, that if a Windows user innocently runs code like

def f(path):
     # do something...

sys.path_hooks.append(f)

then this has no effect at all, because the function is just skipped.  Sure, I 
now know that I have to clear the cache (or maybe manipulate it in other ways), 
but this behavior still seems confusing. (And on a superficial level, *appear* 
to be non-portable... a script would work on one platform but not on the 
other.)  Now I realize that installing import hooks is not something you'd do 
every day, and probably not for the faint of heart, but still... maybe this 
caveat should be documented somewhere?

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html





More information about the Python-list mailing list