[issue15230] runpy.run_path doesn't set __package__ correctly
report at bugs.python.org
Sat Jul 7 12:47:45 CEST 2012
Nick Coghlan <ncoghlan at gmail.com> added the comment:
Firstly, I think you've identified a real bug with __package__ not being set correctly when using runpy.run_path (and I have updated this issue title accordingly).
I have also created a separate bug report (#15272) for the bizarre behaviour you identified in runpy.run_module - names containing "/" characters should be rejected as invalid.
One of the main reasons you're having trouble though is that you can only do relative imports when inside a package - at the top level (as both of your modules are) relative imports are illegal. By forcing package to "__main__" you are claiming a location in the package namespace of "__main__.__main__" which doesn't make any sense.
The module life cycle problem for functions is covered in #812369. The only reason you're not hitting it in the run_module case is that when "alter_sys" is False, no temporary module is created. For data attributes (the intended use case for runpy), this all works fine regardless, but functions (which retain a reference to the original module namespace) will only work properly with alter_sys turned off. There should probably be a general disclaimer in the module docs that functions and classes are not guaranteed to be valid after using runpy, and importlib.import_module should be used instead for such cases.
#9235 looks into ways the runpy module might be enhanced with a CodeRunner class for other reasons, but the same mechanism could be used to keep the temporary module alive without storing it in sys.modules.
title: runpy.run_path broken: Breaks scoping; pollutes sys.modules; doesn't set __package__ -> runpy.run_path doesn't set __package__ correctly
Python tracker <report at bugs.python.org>
More information about the Python-bugs-list