Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
from collections.abc import Sequence
import dataclasses
import inspect
from inspect import CO_VARARGS
from inspect import CO_VARKEYWORDS
from io import StringIO
import os
from pathlib import Path
Expand Down Expand Up @@ -87,18 +85,19 @@ def name(self) -> str:
def path(self) -> Path | str:
"""Return a path object pointing to source code, or an ``str`` in
case of ``OSError`` / non-existing file."""
if not self.raw.co_filename:
filename = inspect.getfile(self.raw)
if not filename:
return ""
try:
p = absolutepath(self.raw.co_filename)
p = absolutepath(filename)
# maybe don't try this checking
if not p.exists():
raise OSError("path check failed.")
return p
except OSError:
# XXX maybe try harder like the weird logic
# in the standard lib [linecache.updatecache] does?
return self.raw.co_filename
return filename

@property
def fullsource(self) -> Source | None:
Expand All @@ -117,14 +116,17 @@ def getargs(self, var: bool = False) -> tuple[str, ...]:
If 'var' is set True also return the names of the variable and
keyword arguments when present.
"""
# Handy shortcut for getting args.
raw = self.raw
argcount = raw.co_argcount
if var:
argcount += raw.co_kwonlyargcount
argcount += bool(raw.co_flags & CO_VARARGS)
argcount += bool(raw.co_flags & CO_VARKEYWORDS)
return raw.co_varnames[:argcount]
# inspect.getargs merges positional and kwonly into a single list;
# 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.

result = list(args)
if varargs is not None:
result.append(varargs)
if varkw is not None:
result.append(varkw)
return tuple(result)


class Frame:
Expand Down
Loading