Here is a patch with the proposed warning. I think “Error finding module specification” might be a bit better than the current “finding spec”, so I included that change. With the patch, this is what the messages look like:
$ ./python -m package.module
/media/disk/home/proj/python/cpython/Lib/runpy.py:125: RuntimeWarning: 'package.module' found in sys.modules after import of any parent packages, but prior to execution; this may result in unpredictable behaviour
warn(RuntimeWarning(msg))
/media/disk/home/proj/python/cpython/python: Error while finding module specification for 'package.module' (ValueError: package.module.__spec__ is not set)
[Exit 1]
The warning also occurs when running toplevel modules that are already imported:
$ ./python -m runpy
/media/disk/home/proj/python/cpython/Lib/runpy.py:125: RuntimeWarning: 'runpy' found in sys.modules after import of any parent packages, but prior to execution; this may result in unpredictable behaviour
warn(RuntimeWarning(msg))
No module specified for execution
FWIW, to fully avoid the regression and keep my original bug fixed at the same time, I think we would need a way for importlib.util.find_spec() to differentiate its own exceptions (the ValueError for missing __spec__, the ImportError for nonexistent parent package, etc) from exceptions raised by __init__.py code. The exceptions currently raised by find_spec() are not flexible enough for the runpy use case. |