Repository navigation
Description
Feature or enhancement
Proposal:
The inspect module provides a utility CLI that supports dumping module source code to the console, or reporting details of a module's location.
This all works as intended when applied to actual Python source files, but it fails messily when applied to non-source modules. For example, attempting to report an extension module's source code throws an unhandled exception:
$ py -V:3.15 -m inspect _sqlite3
Traceback (most recent call last):
... snipped ...
OSError: source code not available
Attempting to report an extension module's details fails to report the module's origin, because that is looked up via inspect.getsourcefile rather than directly, which gives None for non-source modules:
$ py -V:3.15 -m inspect --details _sqlite3
Target: _sqlite3
Origin: None
Cached: None
Loader: <_frozen_importlib_external.ExtensionFileLoader object at 0x000001ECAC22A190>
(In versions prior to 3.15, the latter command would also throw an exception, complaining that the module had no __cached__ attribute. That only changed in 3.15 due to the fact __cached__ also isn't being set on source modules anymore, so the code changed to query __spec__.cached instead)
Builtin modules are currently special cased to report "Can't get info for builtin modules." both with and without the --details CLI option.
Suggested behavioural improvements:
- support reporting the Target and Origin for all queried items (including those from non-source modules)
- support report the Loader for all modules (including non-source modules)
- for all non-source modules (and objects in non-source modules), emit a message like "X is not a source module, reporting object details", and then emit the same output as the
--detailsoption would produce
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsDone
Activity
[-]Improve inspect CLI module handling of non-source modules[/-][+]Improve inspect module CLI handling of non-source modules[/+]ncoghlan commentedon May 3, 2026
I thought this was going to be a straightforward fix, but found a rabbit hole in the way frozen modules are reported when improving the test suite (they're a rare case where
module.__file__andmodule.__spec__.originreport different things, so their source code might be available depending on how the project is shipped - our own_frozen_importlibsets__file__to report the location ofimport._bootstrap, so source introspection works).I'm going to adjust this such that
OriginandSourceare reported as separate lines in the CLI output, since they can be different.gh-149010: Improve reliability of inspect CLI (#149357)