Setuptools, __init__ and __main__

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 6 18:56:35 EST 2015


Dave Angel wrote:

> And don't name any source code __main__.py,


That's incorrect.

Starting from Python 2.6, __main__.py is reserved for the application main
script in packages. That is, if you design your application as a package
(not a single file) with this structure:


myapplication/
+-- __init__.py
+-- __main__.py
+-- spam.py
+-- eggs.py
+-- cheese.py


the __init__.py file is needed for it to be recognised as a package, and the
__main__.py file is used when running the package. (Everything else is
optional, of course, although it's hard to see why you would bother with a
package instead of a single module if you weren't breaking the code up into
multiple modules.)

In other words, when you run `import myapplication` from within Python, the
__init__.py module is imported. But when you do this from the shell:

python -m myapplication


Python will search the PYTHONPATH, find the myapplication package, and run
myapplication/__main__.py as a script.

Of course, you can also run __main__.py by hand:

python /path/to/the/myapplication/__main__.py


but having Python search the path is more convenient.


> Finally, the mere presence of __init__.py has a special meaning, and
> code in it should probably be limited to doing namespace munging that a
> package may require to keep its public interface simpler.

It's conventional to have an empty __init__.py, but not required. At the
very least __init__.py should contain enough code (perhaps `from
mypackage.spam import *`) to make `import mypackage` useful.



-- 
Steven




More information about the Python-list mailing list