diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index a04759ee0678d0..58afa59e76218a 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -1634,6 +1634,21 @@ def d(): py_warnings.simplefilter("error") d() + def test_only_strings_allowed(self): + with self.assertRaisesRegex( + TypeError, + "Expected an object of type str for 'msg', not 'type'" + ): + @deprecated + class Foo: ... + + with self.assertRaisesRegex( + TypeError, + "Expected an object of type str for 'msg', not 'function'" + ): + @deprecated + def foo(): ... + def setUpModule(): py_warnings.onceregistry.clear() diff --git a/Lib/warnings.py b/Lib/warnings.py index 22a1b16907959f..ce592040a3cea6 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -557,6 +557,10 @@ def __init__( category: type[Warning] | None = DeprecationWarning, stacklevel: int = 1, ) -> None: + if not isinstance(msg, str): + raise TypeError( + f"Expected an object of type str for 'msg', not {type(msg).__name__!r}" + ) self.msg = msg self.category = category self.stacklevel = stacklevel