Add a DeprecationWarning for when warnings.showwarning() is set to a function
that lacks support for the new 'line' argument.
diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py
index 5df0b90..c854d7a 100644
--- a/Lib/test/test_warnings.py
+++ b/Lib/test/test_warnings.py
@@ -461,6 +461,32 @@
module = py_warnings
+class ShowwarningDeprecationTests(BaseTest):
+
+ """Test the deprecation of the old warnings.showwarning() API works."""
+
+ @staticmethod
+ def bad_showwarning(message, category, filename, lineno, file=None):
+ pass
+
+ def test_deprecation(self):
+ # message, category, filename, lineno[, file[, line]]
+ args = ("message", UserWarning, "file name", 42)
+ with test_support.catch_warning(self.module):
+ self.module.filterwarnings("error", category=DeprecationWarning)
+ self.module.showwarning = self.bad_showwarning
+ self.assertRaises(DeprecationWarning, self.module.warn_explicit,
+ *args)
+
+class CShowwarningDeprecationTests(ShowwarningDeprecationTests):
+ module = c_warnings
+
+
+class PyShowwarningDeprecationTests(ShowwarningDeprecationTests):
+ module = py_warnings
+
+
+
def test_main():
py_warnings.onceregistry.clear()
c_warnings.onceregistry.clear()
@@ -471,6 +497,8 @@
CWCmdLineTests, PyWCmdLineTests,
_WarningsTests,
CWarningsDisplayTests, PyWarningsDisplayTests,
+ CShowwarningDeprecationTests,
+ PyShowwarningDeprecationTests,
)
diff --git a/Lib/warnings.py b/Lib/warnings.py
index 3c7357b..cefa961 100644
--- a/Lib/warnings.py
+++ b/Lib/warnings.py
@@ -3,6 +3,7 @@
# Note: function level imports should *not* be used
# in this module as it may cause import lock deadlock.
# See bug 683658.
+import inspect
import linecache
import sys
import types
@@ -21,7 +22,7 @@
category = DeprecationWarning
warn(message, category, stacklevel+1)
-def showwarning(message, category, filename, lineno, file=None, line=None):
+def _show_warning(message, category, filename, lineno, file=None, line=None):
"""Hook to write a warning to a file; replace if you like."""
if file is None:
file = sys.stderr
@@ -29,6 +30,9 @@
file.write(formatwarning(message, category, filename, lineno, line))
except IOError:
pass # the file (probably stderr) is invalid - this warning gets lost.
+# Keep a worrking version around in case the deprecation of the old API is
+# triggered.
+showwarning = _show_warning
def formatwarning(message, category, filename, lineno, line=None):
"""Function to format a warning the standard way."""
@@ -259,6 +263,15 @@
"Unrecognized action (%r) in warnings.filters:\n %s" %
(action, item))
# Print message and context
+ if inspect.isfunction(showwarning):
+ arg_spec = inspect.getargspec(showwarning)
+ if 'line' not in arg_spec.args:
+ showwarning_msg = ("functions overriding warnings.showwarning() "
+ "must support the 'line' argument")
+ if message == showwarning_msg:
+ _show_warning(message, category, filename, lineno)
+ else:
+ warn(showwarning_msg, DeprecationWarning)
showwarning(message, category, filename, lineno)