Default `warnings.showwarning` always used when interpreter session is cleaning up
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 77.2k
- Forks
- 35.9k
- Métriques de merge des PR
- Métriques de PR en attente
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
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par le script de reproduction dans l’issue et comparez son chemin normal d’avertissement au comportement de nettoyage de l’interpréteur. Examinez la PR liée gh-150944 pour voir la portée proposée ; c’est terminé lorsque le gestionnaire personnalisé warnings.showwarning est systématiquement respecté pendant le nettoyage, avec une couverture pour le reproducer.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- backend
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 25/100