简体   繁体   English

没有__init__的Python包

[英]Python package without __init__

I pip install -ed the flufl.enum Python package and I noticed that it works despite missing a flufl/__init__.py module as regular Python packages. pip install -ed flufl.enum Python包,我注意到它虽然缺少一个flufl/__init__.py模块作为常规Python包,但仍然flufl/__init__.py Even stranger is this: 更奇怪的是:

>>> import flufl
>>> flufl
<module 'flufl' (built-in)>

I tried to reproduce this creating foo/bar/__init__.py without foo/__init__.py and (predictably) import foo fails. 我试图重现这个创建foo/bar/__init__.py而没有foo/__init__.py和(可预测) import foo失败。 How does flufl do it? flufl是如何做到的?

the magic is done in the flufl.enum-3.2-py2.7-nspkg.pth file, which is put into site-packages by "pip install": 魔术是在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)

pth files are evaluated at startup. pth文件在启动时进行评估。 In particular, this file creates a new module named "flufl" and puts it into sys.modules. 特别是,此文件创建一个名为“flufl”的新模块并将其放入sys.modules中。 That also explains why you see it as "built-in": 这也解释了为什么你把它看作“内置”:

>>> import new
>>> new.module('foo')
<module 'foo' (built-in)>

I don't get it 我不明白

ls /Users/sbo/lib/python2.7/site-packages/flufl.enum-3.2-py2.7.egg/flufl/
__init__.py   __init__.pyc  enum/

Did you compile flufl.enum together with python ? 你有没有和python一起编译flufl.enum? It's the only way it can be a builtin module. 这是它可以成为内置模块的唯一方式。

By the way, I actually read a PEP where packages could skip the init, but I don't remember if it was approved, rejected, or under scrutiny. 顺便说一句,我实际上读了一个PEP,其中包可以跳过init,但我不记得它是否被批准,拒绝或受到审查。

flufl is just a namespace package, declared in the egg's namespace_packages.txt flufl只是一个命名空间包,在egg的namespace_packages.txt中声明

If you look at its source tree it actually does have flufl/__init__.py , but for distribution as an egg it looks like it's not necessary due to setuptools magic. 如果你看一下它的源代码树,它实际上确实有flufl/__init__.py ,但是由于setuptools魔法,它看起来像没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM