Skip to content

bpo-29564: warnings suggests to enable tracemalloc #10486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 13, 2018
Merged
Show file tree
Hide file tree
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
25 changes: 20 additions & 5 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -897,12 +897,27 @@ def func():
func()
"""))

res = assert_python_ok('-Wd', '-X', 'tracemalloc=2', support.TESTFN)
def run(*args):
res = assert_python_ok(*args)
stderr = res.err.decode('ascii', 'replace')
stderr = '\n'.join(stderr.splitlines())

stderr = res.err.decode('ascii', 'replace')
# normalize newlines
stderr = '\n'.join(stderr.splitlines())
stderr = re.sub('<.*>', '<...>', stderr)
# normalize newlines
stderr = re.sub('<.*>', '<...>', stderr)
return stderr

# tracemalloc disabled
stderr = run('-Wd', support.TESTFN)
expected = textwrap.dedent('''
{fname}:5: ResourceWarning: unclosed file <...>
f = None
ResourceWarning: Enable tracemalloc to get the object allocation traceback
''')
expected = expected.format(fname=support.TESTFN).strip()
self.assertEqual(stderr, expected)

# tracemalloc enabled
stderr = run('-Wd', '-X', 'tracemalloc=2', support.TESTFN)
expected = textwrap.dedent('''
{fname}:5: ResourceWarning: unclosed file <...>
f = None
Expand Down
23 changes: 17 additions & 6 deletions Lib/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ def _showwarnmsg_impl(msg):
pass

def _formatwarnmsg_impl(msg):
s = ("%s:%s: %s: %s\n"
% (msg.filename, msg.lineno, msg.category.__name__,
msg.message))
category = msg.category.__name__
s = f"{msg.filename}:{msg.lineno}: {category}: {msg.message}\n"

if msg.line is None:
try:
Expand All @@ -55,11 +54,20 @@ def _formatwarnmsg_impl(msg):
if msg.source is not None:
try:
import tracemalloc
tb = tracemalloc.get_object_traceback(msg.source)
# Logging a warning should not raise a new exception:
# catch Exception, not only ImportError and RecursionError.
except Exception:
# When a warning is logged during Python shutdown, tracemalloc
# and the import machinery don't work anymore
# don't suggest to enable tracemalloc if it's not available
tracing = True
tb = None
else:
tracing = tracemalloc.is_tracing()
try:
tb = tracemalloc.get_object_traceback(msg.source)
except Exception:
# When a warning is logged during Python shutdown, tracemalloc
# and the import machinery don't work anymore
tb = None

if tb is not None:
s += 'Object allocated at (most recent call last):\n'
Expand All @@ -77,6 +85,9 @@ def _formatwarnmsg_impl(msg):
if line:
line = line.strip()
s += ' %s\n' % line
elif not tracing:
s += (f'{category}: Enable tracemalloc to get the object '
f'allocation traceback\n')
Copy link
Member

@pablogsal pablogsal Nov 12, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: Would be useful to add to this sentence how to enable tracemalloc quickly? For example:

s += (f'{category}: Enable tracemalloc to get the object '
      f'allocation traceback (i.e. -X tracemalloc=N_FRAMES)\n')

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are multiple ways to enable tracemalloc: PYTHONTRACEMALLOC=nframe and python3 -X tracemalloc=nframe. It's non-obvious where -X tracemalloc comes from, nor what is nframe, etc.

"ResourceWarning: Enable tracemalloc to get the object allocation traceback" is already 74 characters long, and I like to fit into 80 columns :-)

IMHO giving the hint "enable tracemalloc" should be enough to someone motivated to fix a ResourceWarning bug :)

@pablogsal: What do you think? Is the current PR good now?

Copy link
Member

@pablogsal pablogsal Nov 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup :)

I am convinced by your 80 columns argument :D

return s

# Keep a reference to check if the function was replaced
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The warnings module now suggests to enable tracemalloc if the source is
specified, the tracemalloc module is available, but tracemalloc is not
tracing memory allocations.