Skip to content

bpo-35178: Ensure custom formatwarning function can receive line as positional argument #12033

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 3 commits into from
Mar 1, 2019
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
19 changes: 19 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,25 @@ def test_showwarning(self):
file_object, expected_file_line)
self.assertEqual(expect, file_object.getvalue())

def test_formatwarning_override(self):
# bpo-35178: Test that a custom formatwarning function gets the 'line'
# argument as a positional argument, and not only as a keyword argument
def myformatwarning(message, category, filename, lineno, text):
return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'

file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
file_line = linecache.getline(file_name, line_num).strip()
message = 'msg'
category = Warning
file_object = StringIO()
expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \
f':t={file_line}'
with support.swap_attr(self.module, 'formatwarning', myformatwarning):
self.module.showwarning(message, category, file_name, line_num,
file_object, file_line)
self.assertEqual(file_object.getvalue(), expected)


class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
module = c_warnings
Expand Down
2 changes: 1 addition & 1 deletion Lib/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def _formatwarnmsg(msg):
if fw is not _formatwarning_orig:
# warnings.formatwarning() was replaced
return fw(msg.message, msg.category,
msg.filename, msg.lineno, line=msg.line)
msg.filename, msg.lineno, msg.line)
return _formatwarnmsg_impl(msg)

def filterwarnings(action, message="", category=Warning, module="", lineno=0,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Ensure custom :func:`warnings.formatwarning` function can receive `line` as
positional argument. Based on patch by Tashrif Billah.