Skip to content

gh-149117: Set ImportError.name on errors from runpy.run_module/run_path#149159

Open
mattwang44 wants to merge 1 commit intopython:mainfrom
mattwang44:gh-149117-runpy-importerror-name
Open

gh-149117: Set ImportError.name on errors from runpy.run_module/run_path#149159
mattwang44 wants to merge 1 commit intopython:mainfrom
mattwang44:gh-149117-runpy-importerror-name

Conversation

@mattwang44
Copy link
Copy Markdown
Contributor

@mattwang44 mattwang44 commented Apr 29, 2026

runpy.run_module() and runpy.run_path() previously raised ImportError with name=None. They now set name to the requested module name, matching a regular import.

>>> try: 
...     runpy.run_module("nonexistent")
... except ImportError as e:
...     print(repr(e.name))
'nonexistent'   # was None

The name= kwarg is gated on issubclass(error, ImportError) so the private _Error sentinel used by _run_module_as_main() is unaffected.

runpy.run_module() and runpy.run_path() now set the `name` attribute
of the ImportError they raise to the requested module name, matching
the behaviour of a regular import statement (previously `name` was
always `None`, which broke introspection).

The `name=` kwarg is gated on `issubclass(error, ImportError)` because
`_get_module_details()` is also used by `_run_module_as_main()` with
a private `_Error` sentinel class. `_Error` does not subclass
ImportError, and `BaseException.__init__` rejects unknown kwargs at
the C level, so passing `name=` unconditionally would break the
`python -m foo` codepath.
@read-the-docs-community
Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #32471141 | 📁 Comparing 2cb073f against main (8851a06)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant