[Python-Dev] PEP 302, PEP 338 and imp.getloader (was Re: a Python interface for the AST (WAS: DRAFT: python-dev...)
Phillip J. Eby
pje at telecommunity.com
Wed Nov 23 19:25:44 CET 2005
At 11:51 PM 11/23/2005 +1000, Nick Coghlan wrote:
>The key thing that is missing is the "imp.getloader" functionality discussed
>at the end of PEP 302.
This isn't hard to implement per se; setuptools for example has a
'get_importer' function, and going from importer to loader is simple:
def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for hook in sys.path_hooks:
try:
importer = hook(path_item)
except ImportError:
pass
else:
break
else:
importer = None
sys.path_importer_cache.setdefault(path_item,importer)
if importer is None:
try:
importer = ImpWrapper(path_item)
except ImportError:
pass
return importer
So with the above function you could do something like:
def get_loader(fullname, path):
for path_item in path:
try:
loader = get_importer(path_item).find_module(fullname)
if loader is not None:
return loader
except ImportError:
continue
else:
return None
in order to implement the rest.
>** I'm open to suggestions on how to deal with argv[0] and __file__. They
>should be set to whatever __file__ would be set to by the module loader, but
>the Importer Protocol in PEP 302 doesn't seem to expose that information. The
>current proposal is a compromise that matches the existing behaviour of -m
>(which supports scripts like regrtest.py) while still giving a meaningful
>value for scripts which are not part of the normal filesystem.
Ugh. Those are tricky, no question. I can think of several simple answers
for each, all of which are wrong in some way. :)
More information about the Python-Dev
mailing list