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.

Title: `python -m` semantics conflict with `__file__`'s being optional
Type: behavior Stage:
Components: Interpreter Core, Library (Lib) Versions: Python 3.10, Python 3.9, Python 3.8
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: William.Schwartz, eric.snow, ncoghlan
Priority: normal Keywords:

Created on 2020-11-10 16:52 by William.Schwartz, last changed 2022-04-11 14:59 by admin.

Messages (1)
msg380689 - (view) Author: William Schwartz (William.Schwartz) * Date: 2020-11-10 16:52
`python -m mod` sets `sys.argv[0]` to the `mod.__file__` according to

> If ["-m"] is given, the first element of sys.argv will be the full path to the module file (while the module file is being located, the first element will be set to "-m").

But `__file__` may not exist according to

> __file__ is optional. If set, this attribute’s value must be a string. The import system may opt to leave __file__ unset if it has no semantic meaning (e.g. a module loaded from a database).

More technically, `__spec__.origin` is the source of `__file__`, and the former may be `None`, according to

> (__file__)
> Name of the place from which the module is loaded, e.g. “builtin” for built-in modules and the filename for modules loaded from source. Normally “origin” should be set, but it may be None (the default) which indicates it is unspecified (e.g. for namespace packages).

`python -m mod` sets sys.argv[0] to `mod.__spec__.origin` at Lib/

It seems clear to me that the code is doing the right thing relative to the documentation for `-m`. But as #26388 and show, embedded Python runs into the semantic conflict with the documented behavior of `__spec__.origin` and `__file__`.

My proposed resolution of this contradiction is to set `sys.argv[0] = sys.orig_argv[0]` or, even better, `sys.argv[0] = sys.executable` when `PyConfig.run_module` is set but the named module's `__spec__.origin` is `None`.
Date User Action Args
2022-04-11 14:59:38adminsetgithub: 86481
2020-11-10 21:55:49brett.cannonsetnosy: - brett.cannon
2020-11-10 16:52:44William.Schwartzcreate