Skip to content

Use inspect module in Code class instead of direct co_* attribute access#14536

Open
nicoddemus wants to merge 1 commit into
pytest-dev:mainfrom
nicoddemus:use-inspect-in-Code
Open

Use inspect module in Code class instead of direct co_* attribute access#14536
nicoddemus wants to merge 1 commit into
pytest-dev:mainfrom
nicoddemus:use-inspect-in-Code

Conversation

@nicoddemus
Copy link
Copy Markdown
Member

@nicoddemus nicoddemus commented May 30, 2026

As a follow-up to #14493, replace direct co_* accesses in Code.path and Code.getargs with inspect.getfile and inspect.getargs respectively, delegating argument-decoding logic to well-tested stdlib APIs rather than re-implementing it with raw bitmask arithmetic.

Code.firstlineno and Code.name still access co_firstlineno and co_name directly: the inspect module has no equivalent for these that does not require reading the source file from disk, which would regress correctness for compile()'d code and performance for every traceback formatting path.

@nicoddemus nicoddemus added the skip news used on prs to opt out of the changelog requirement label May 30, 2026
As a follow-up to pytest-dev#14493, replace direct co_* accesses in Code.path and
Code.getargs with inspect.getfile and inspect.getfullargspec respectively,
delegating argument-decoding logic to well-tested stdlib APIs rather than
re-implementing it with raw bitmask arithmetic.

Code.firstlineno and Code.name still access co_firstlineno and co_name
directly: the inspect module has no equivalent for these that does not
require reading the source file from disk, which would regress correctness
for compile()'d code and performance for every traceback formatting path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@nicoddemus nicoddemus force-pushed the use-inspect-in-Code branch from a121a89 to fa59a08 Compare May 30, 2026 12:42
Comment thread src/_pytest/_code/code.py
# co_argcount is needed to exclude kwonly when var=False.
args, varargs, varkw = inspect.getargs(self.raw)
if not var:
return tuple(args[: self.raw.co_argcount])
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still access co_argcount here, but in the end using inspect.getargs seems more future-proof than bitwise handling of co_flags.

@nicoddemus nicoddemus marked this pull request as ready for review May 30, 2026 13:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip news used on prs to opt out of the changelog requirement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant