Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. How does flufl do it?

like image 927
gsakkis Avatar asked Nov 13 '11 10:11

gsakkis


1 Answers

the magic is done in the flufl.enum-3.2-py2.7-nspkg.pth file, which is put into site-packages by "pip install":

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. In particular, this file creates a new module named "flufl" and puts it into sys.modules. That also explains why you see it as "built-in":

>>> import new
>>> new.module('foo')
<module 'foo' (built-in)>
like image 56
Antonio Cuni Avatar answered Oct 20 '22 07:10

Antonio Cuni