This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: _warnings.warn_explicit() should try to import the warnings module
Type: enhancement Stage:
Components: Versions: Python 3.6
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: python-dev, vstinner
Priority: normal Keywords: patch

Created on 2016-03-19 13:34 by vstinner, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
warnings_import.patch vstinner, 2016-03-19 13:34
Messages (2)
msg262049 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2016-03-19 13:34
The issue #26567 enhanced the warnings module to pass the destroyed object on ResourceWarning. The implementation to log the traceback where the object was allocated is non trivial, so I chose to only implement it in Python.

Problem: _warnings.warn_explicit() is lazy, it tries to get the warnings module from sys.modules, but it uses its own logger if the warnings is not imported yet.

As a consequence, the traceback where the object was allocated is only logged if tracemalloc is tracing Python memory allocations *and* if the warnings module is already imported.

I suggest to modify _warnings.warn_explicit() to import the warnings if it's not imported yet.

There are maybe issues to import a module during Python finalization? A comprise is to not try to import when Python finalization has started.

Example:
---
#import warnings
import tracemalloc
tracemalloc.start(10)
f = open("/etc/issue")
f = None
---

Current output:
---
x.py:5: ResourceWarning: unclosed file <_io.TextIOWrapper name='/etc/issue' mode='r' encoding='UTF-8'>
  f = None
---

Output if you uncomment the "import warnings":
---
x.py:5: ResourceWarning: unclosed file <_io.TextIOWrapper name='/etc/issue' mode='r' encoding='UTF-8'>
  f = None
Object allocated at (most recent call first):
  File "x.py", lineno 4
    f = open("/etc/issue")
---

Attached patch tries to import warnings if source object is set but not after the Pythin finalization has started.
msg262219 - (view) Author: Roundup Robot (python-dev) (Python triager) Date: 2016-03-22 23:56
New changeset 53343d095f78 by Victor Stinner in branch 'default':
_warnings.warn_explicit(): try to import warnings
https://hg.python.org/cpython/rev/53343d095f78
History
Date User Action Args
2022-04-11 14:58:28adminsetgithub: 70779
2016-03-22 23:56:19vstinnersetstatus: open -> closed
resolution: fixed
2016-03-22 23:56:04python-devsetnosy: + python-dev
messages: + msg262219
2016-03-19 13:34:14vstinnercreate