Repository navigation
gh-75221: Search __main__ only in the executed directory or zipfile - #155256
Conversation
…file runpy.run_path() and the execution of a directory or a zipfile searched the __main__ module in the whole sys.path, so an existing __main__ module located elsewhere could be executed instead of failing. As a result, running Lib/test/test_runpy.py directly ran the whole test suite. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Documentation build overview
454 files changed ·
|
|
This PR is stale because it has been open for 90 days with no activity. |
ncoghlan
left a comment
There was a problem hiding this comment.
LGTM (my only concern was the new pkgutil dependency, and I convinced myself that the reduction in potentially confusing behaviour is worth the implicit imports of additional modules that are frequently going to be imported by the code being executed anyway)
| kwargs = {"name": main_name} if issubclass(error, ImportError) else {} | ||
| saved_main = sys.modules[main_name] | ||
| del sys.modules[main_name] | ||
| from pkgutil import get_importer |
There was a problem hiding this comment.
The pkgutil dependency gave me a momentary pause for concern, but that's still a fairly low level module. Compared to importing runpy itself, 3.15 shows me the following extra imports:
import time: 61 | 61 | itertools
import time: 82 | 82 | keyword
import time: 40 | 40 | _operator
import time: 194 | 233 | operator
import time: 119 | 119 | reprlib
import time: 47 | 47 | _collections
import time: 658 | 1198 | collections
import time: 32 | 32 | _functools
import time: 363 | 394 | functools
import time: 128 | 128 | _weakrefset
import time: 234 | 361 | weakref
import time: 269 | 2221 | pkgutil
There was a problem hiding this comment.
Good catch! run_path() already imported pkgutil, but _run_module_as_main() (used for a directory or a zipfile) did not. Import added 2 ms. I replaced it with importlib.machinery.PathFinder.find_spec() which is already imported.
It does not import additional modules at startup.
serhiy-storchaka
left a comment
There was a problem hiding this comment.
Thank you for the review, @ncoghlan.
| kwargs = {"name": main_name} if issubclass(error, ImportError) else {} | ||
| saved_main = sys.modules[main_name] | ||
| del sys.modules[main_name] | ||
| from pkgutil import get_importer |
There was a problem hiding this comment.
Good catch! run_path() already imported pkgutil, but _run_module_as_main() (used for a directory or a zipfile) did not. Import added 2 ms. I replaced it with importlib.machinery.PathFinder.find_spec() which is already imported.
runpy.run_path()and the execution of a directory or a zipfile searched the__main__module in the wholesys.path, so an existing__main__module located elsewhere could be executed instead of failing.As a result, running
Lib/test/test_runpy.pydirectly ran the whole test suite.The
__main__module is now searched only insys.path[0]-- the executed directory or zipfile.