Default `warnings.showwarning` always used when interpreter session is cleaning up
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
Hey!
I'm not sure this is a bug, exactly, or just behaviour that is not documented well (or at all, despite me looking I couldn't really find anything on it), but I recently ran into it and was scratching my head for a good hour.
The "issue" if it even is one, is that the default warnings.showwarning handler is always called when the main scope for the interpreter is getting cleaned up, even if there is a custom showwarning hook.
I noticed this by having some resource leak messages in the __del__ calls for some objects, and noticed that they only trigger the proper handler if they are triggered in any scope under the main scope, but if done so in the main scope they always use the default handler.
The following code reproduces the behaviour:
import warnings
def _warning_handler(message, category, filename, lineno, output_file, line):
warn = warnings.formatwarning(message, category, filename, lineno, line)
print(f'😺: {warn}', file = output_file)
warnings.showwarning = _warning_handler
def meow():
print(f'Warning handler is: {warnings.showwarning.__code__.co_filename}')
warnings.warn('meow')
class Cat:
def __del__(self):
print(f'Warning handler is: {warnings.showwarning.__code__.co_filename}')
warnings.warn('nya')
meow()
cat = Cat()
The output of this code is:
Warning handler is: /tmp/mvp.py
😺: /tmp/mvp.py:11: UserWarning: meow
warnings.warn('meow')
Warning handler is: /tmp/mvp.py
/tmp/mvp.py:16: UserWarning: nya
CPython versions tested on:
3.14
Operating systems tested on:
Linux
Linked PRs
- gh-150944
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducing script in the issue and compare its normal warning path with interpreter cleanup behavior. Review linked PR gh-150944 to see the proposed scope; done means the custom warnings.showwarning handler is consistently respected during cleanup, with coverage for the reproducer.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100