From 7bb1e1a23634bae81bf76fdb34e9f9f7e59b3793 Mon Sep 17 00:00:00 2001 From: Xuehai Pan Date: Mon, 7 Apr 2025 00:37:37 +0800 Subject: gh-132159: Do not shadow user arguments in generated `__new__` by `@warnings.deprecated` (#132160) --- Lib/test/test_warnings/__init__.py | 19 +++++++++++++++++++ Lib/warnings.py | 2 +- .../2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index 6f4c569..de4280c 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -1653,6 +1653,25 @@ class DeprecatedTests(PyPublicAPITests): instance = Child(42) self.assertEqual(instance.a, 42) + def test_do_not_shadow_user_arguments(self): + new_called = False + new_called_cls = None + + @deprecated("MyMeta will go away soon") + class MyMeta(type): + def __new__(mcs, name, bases, attrs, cls=None): + nonlocal new_called, new_called_cls + new_called = True + new_called_cls = cls + return super().__new__(mcs, name, bases, attrs) + + with self.assertWarnsRegex(DeprecationWarning, "MyMeta will go away soon"): + class Foo(metaclass=MyMeta, cls='haha'): + pass + + self.assertTrue(new_called) + self.assertEqual(new_called_cls, 'haha') + def test_existing_init_subclass(self): @deprecated("C will go away soon") class C: diff --git a/Lib/warnings.py b/Lib/warnings.py index df84425..0307f89 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -597,7 +597,7 @@ class deprecated: original_new = arg.__new__ @functools.wraps(original_new) - def __new__(cls, *args, **kwargs): + def __new__(cls, /, *args, **kwargs): if cls is arg: warn(msg, category=category, stacklevel=stacklevel + 1) if original_new is not object.__new__: diff --git a/Misc/NEWS.d/next/Library/2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst b/Misc/NEWS.d/next/Library/2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst new file mode 100644 index 0000000..8cec76e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst @@ -0,0 +1 @@ +Do not shadow user arguments in generated :meth:`!__new__` by decorator :class:`warnings.deprecated`. Patch by Xuehai Pan. -- cgit v0.12