From 0ed6f4ef0f643c0d6a6c8c42d07a02e3d9fa992c Mon Sep 17 00:00:00 2001 From: Xuehai Pan Date: Mon, 7 Apr 2025 00:05:45 +0800 Subject: [PATCH 1/2] Do not shadow user arguments in generated `__new__` by `@warnings.deprecated` --- Lib/test/test_warnings/__init__.py | 19 +++++++++++++++++++ Lib/warnings.py | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index 6f4c569d247601..de4280cd22f0c9 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -1653,6 +1653,25 @@ class Child(Base, Mixin): 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 df844253ab4e6d..0307f89dafef5a 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -597,7 +597,7 @@ def __call__(self, arg, /): 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__: From 8e625d52f510ad422de9d66f3dd541369f13e363 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Sun, 6 Apr 2025 16:12:53 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../next/Library/2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2025-04-06-16-12-49.gh-issue-132159.WvBfBm.rst 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 00000000000000..8cec76e9b47405 --- /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.