Skip to content

Improve inspect module CLI handling of non-source modules #149010

@ncoghlan

Description

@ncoghlan

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 --details option 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.15new features, bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytriagedThe issue has been accepted as valid by a triager.type-featureA feature request or enhancement

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions