我使用pip install了flufl.enum Python软件包,我注意到尽管错过了flufl/__init__.py常规Python软件包的模块,但它仍能正常工作.更奇怪的是:
>>> import flufl
>>> flufl
<module 'flufl' (built-in)>
Run Code Online (Sandbox Code Playgroud)
我试图在foo/bar/__init__.py没有foo/__init__.py(并且可预测)import foo失败的情况下重现这种创造.怎么flufl做?
小智 19
魔术是在flufl.enum-3.2-py2.7-nspkg.pth文件中完成的,该文件通过"pip install"放入site-packages:
import sys,new,os
p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('flufl',))
ie = os.path.exists(os.path.join(p,'__init__.py'))
m = not ie and sys.modules.setdefault('flufl',new.module('flufl'))
mp = (m or []) and m.__dict__.setdefault('__path__',[])
(p not in mp) and mp.append(p)
Run Code Online (Sandbox Code Playgroud)
pth文件在启动时进行评估.特别是,此文件创建一个名为"flufl"的新模块并将其放入sys.modules中.这也解释了为什么你把它看作"内置":
>>> import new
>>> new.module('foo')
<module 'foo' (built-in)>
Run Code Online (Sandbox Code Playgroud)