Setuptools, __init__ and __main__

Dave Angel davea at davea.name
Fri Feb 6 19:17:18 EST 2015


On 02/06/2015 06:56 PM, Steven D'Aprano wrote:
> 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.

That's the main thing I just didn't know. I've seen __main__ from the 
perspective of the
if __name__ == "__main__":
     where it's just an alias for the actual script name, and I didn't 
realize the duality.

Sorry for the noise.


>
> 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.
>
>
>


-- 
DaveA



More information about the Python-list mailing list