Skip to content

Commit 83070aa

Browse files
[3.13] gh-132159: Do not shadow user arguments in generated __new__ by @warnings.deprecated (GH-132160) (#132163)
gh-132159: Do not shadow user arguments in generated `__new__` by `@warnings.deprecated` (GH-132160) (cherry picked from commit 7bb1e1a) Co-authored-by: Xuehai Pan <XuehaiPan@pku.edu.cn>
1 parent f7ab4eb commit 83070aa

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Lib/test/test_warnings/__init__.py

+19
Original file line numberDiff line numberDiff line change
@@ -1628,6 +1628,25 @@ class Child(Base, Mixin):
16281628
instance = Child(42)
16291629
self.assertEqual(instance.a, 42)
16301630

1631+
def test_do_not_shadow_user_arguments(self):
1632+
new_called = False
1633+
new_called_cls = None
1634+
1635+
@deprecated("MyMeta will go away soon")
1636+
class MyMeta(type):
1637+
def __new__(mcs, name, bases, attrs, cls=None):
1638+
nonlocal new_called, new_called_cls
1639+
new_called = True
1640+
new_called_cls = cls
1641+
return super().__new__(mcs, name, bases, attrs)
1642+
1643+
with self.assertWarnsRegex(DeprecationWarning, "MyMeta will go away soon"):
1644+
class Foo(metaclass=MyMeta, cls='haha'):
1645+
pass
1646+
1647+
self.assertTrue(new_called)
1648+
self.assertEqual(new_called_cls, 'haha')
1649+
16311650
def test_existing_init_subclass(self):
16321651
@deprecated("C will go away soon")
16331652
class C:

Lib/warnings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,7 @@ def __call__(self, arg, /):
589589
original_new = arg.__new__
590590

591591
@functools.wraps(original_new)
592-
def __new__(cls, *args, **kwargs):
592+
def __new__(cls, /, *args, **kwargs):
593593
if cls is arg:
594594
warn(msg, category=category, stacklevel=stacklevel + 1)
595595
if original_new is not object.__new__:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Do not shadow user arguments in generated :meth:`!__new__` by decorator :class:`warnings.deprecated`. Patch by Xuehai Pan.

0 commit comments

Comments
 (0)