I use __init__.py to run checks when I do from myprojects.something import blabla.
Today I started using pyzmq and I wanted to see what’s going on behind the scenes. So I browsed the code in github and I find (for me) some strange usage of __init__.py there that I cannot explain myself.
For example zmq/core/__init__.py. What’s the point of adding in zmq.core.__all__ the __all__‘s value of zmq.core.constants, zmq.core.error, zmq.core.message, etc.?
In zmq/__init__.py I see at the end
__all__ = ['get_includes'] + core.__all__
where get_includes is a function which basically returns a list with the directory of the module and the utils directory in the parent directory.
What’s the point of that? What has __init.py__ achieved by doing that?
The
__all__is for when someone doesfrom module import *as documented here.One use for
__all__is a tool for package builders to allow them to structure their package in a way that works for them while making it convenient for users. Specifically in the case of pyzmq, it lets you write code such as:Rather than having to use the full dotted module name:
The package designers of pyzmq are using
__all__to promote namespace elements from nested modules up to the top level of their namespace so the user isn’t bothered by the structure of their package.