[Python-Dev] how to find the file path to an extension module at init time?
Stefan Behnel
stefan_ml at behnel.de
Mon Nov 14 14:27:16 CET 2011
mark florisson, 14.11.2011 12:55:
> On 14 November 2011 08:18, Stefan Behnel wrote:
>> "Martin v. Löwis", 13.11.2011 21:46:
>>>>
>>>> I'm asking specifically because I'd like to properly implement __file__
>>>> in Cython modules at module init time.
>>>
>>> Why do you need to implement __file__? Python will set it eventually to
>>> its correct value, no?
>>
>> Well, yes, eventually. However, almost all real world usages are at module
>> init time, not afterwards. So having CPython set it after running through
>> the module global code doesn't help much.
>
> Perhaps Cython could detect use of __file__ at module scope (if this
> package context function is not available), and if it's used it tries
> to use something akin to imp.find_module(__name__) to find the path to
> the file and set __file__ manually.
It's problematic. Depending on the import hooks that are in use, a second
search for the already loaded but not yet instantiated module may
potentially trigger a second try to load it. And if the module is already
put into sys.modules, a second search may not return a helpful result.
Also, running a full import of "imp" along the way may have additional side
effects, and the C-API doesn't have a way to just search for the path of a
module.
> Would this be feasible for python < 3.3?
It would certainly not be more than a work-around, but it could be made to
work "well enough" in many cases. I'd definitely prefer having something
that really works in both 2.7.x and 3.3+ over a half-baked solution in all
of Py2.x.
Stefan
More information about the Python-Dev
mailing list