This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mandolaerik
Recipients docs@python, mandolaerik
Date 2021-07-02.14:08:58
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1625234939.05.0.135731046929.issue44552@roundup.psfhosted.org>
In-reply-to
Content
I can find partial information on how Python treats __main__.py here: https://docs.python.org/3/library/__main__.html

However, it is not documented how python handles __main__.py when passing the Python package to the interpreter without -m. If I have a program defined by /tmp/foo/bar.py and a file /tmp/foo/__main__.py, and I run

python /tmp/foo

... then Python will run __main__.py, with /tmp/foo prepended to sys.path.

I find this behaviour unfortunate; to me it would make more sense to prepend /tmp to sys.path, because then "python /tmp/foo" would be equivalent to "PYTHONPATH=/tmp python -m foo". With the current behaviour, if __main__.py wants to import bar.py, then it must write 'import bar' or 'import foo.bar' depending on whether the interpreter was invoked with -m.

Unfortunately, by Hyrum's Law, you can find people describing and encouraging reliance upon the current undocumented behaviour, e.g.:
https://www.geeksforgeeks.org/usage-of-__main__-py-in-python/
so perhaps the behaviour can't be changed that easily. Therefore, my request is to document how it works.
History
Date User Action Args
2021-07-02 14:08:59mandolaeriksetrecipients: + mandolaerik, docs@python
2021-07-02 14:08:59mandolaeriksetmessageid: <1625234939.05.0.135731046929.issue44552@roundup.psfhosted.org>
2021-07-02 14:08:59mandolaeriklinkissue44552 messages
2021-07-02 14:08:58mandolaerikcreate