You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
warnings.warn's skip_file_prefixes doesn't work when provided __file__. #126209
I was attempting to make warning.warn skip all frames in the calling file by setting skip_file_prefixes=(__file__,). Frustratingly it wasn't working as expected and was blaming an intermediate frame in the file I was trying to skip. Looking at Lib/warnings.py I was confused as to why it wasn't working. After some digging I discovered there is a parallel C implementation in Python/_warnings.c.
The following script demonstrates the difference between the two implementations:
importsys# Uncomment to compare the C and Py implementation of warnings.warn.# sys.modules["_warnings"] = Noneimportwarnings# Desired input which works as expected with the Py impl, but not the C impl.skip_file_prefixes=(__file__,)
# Hack to make the C implementation match the Py behavior:# skip_file_prefixes=(__file__[:-1],) defccc():
warnings.warn("Hello", UserWarning, skip_file_prefixes=skip_file_prefixes)
defbbb():
ccc()
defaaa():
bbb()
aaa()
There is a slight implementation difference between Python/_warnings.c:is_filename_to_skip and Lib/warnings.py:_is_filename_to_skip. The Python implementation is uses filename.startswith(prefix)1 while the C implementation uses PyUnicode_Tailmatch(filename, prefix, 0, -1, -1)2. It looks like the C implementation should be something like PyUnicode_Tailmatch(filename, prefix, 0, PY_SSIZE_T_MAX, -1).
Activity
zsaladin commentedon Nov 2, 2024
I will take a look
corona10 commentedon Nov 2, 2024
@zsaladin is a first-time contributor who is participating in the PyCon KR sprint today.
I will help him contribute to this issue :)
pythongh-126209: Fix the inconsistent results of c and python impleme…
pythongh-126209: Fix the inconsistent results of c and python impleme…
pythongh-126209: Add assert for length of warn result
pythongh-126209: Add a test for inconsistent behaviour of `skip_file_…
gh-126209: Fix inconsistency of `skip_file_prefixes` in `warnings.war…
pythongh-126209: Fix inconsistency of `skip_file_prefixes` in `warnin…
hugovk commentedon Jan 7, 2025
Thank you @nairb774 for reporting, @zsaladin for the PR, and @corona10 for helping :)
pythongh-126209: Fix inconsistency of `skip_file_prefixes` in `warnin…