Skip to content

Commit bd583ef

Browse files
Nateambv
Nate
authored andcommitted
bpo-29581: Make ABCMeta.__new__ pass **kwargs to type.__new__ (#527)
Many metaclasses in the standard library don't play nice with __init_subclass__. This bug makes ABCMeta in particular with __init_subclass__, which is an 80/20 solution for me personally. AFAICT, a general solution to this problem requires updating all metaclasses in the standard library to make sure they pass **kwargs to type.__new__, whereas this PR only fixes ABCMeta. For context, see https://bugs.python.org/issue29581. * added a test combining ABCMeta and __init_subclass__ * Added NEWS item
1 parent b4e9087 commit bd583ef

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

Lib/abc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,8 @@ class ABCMeta(type):
129129
# external code.
130130
_abc_invalidation_counter = 0
131131

132-
def __new__(mcls, name, bases, namespace):
133-
cls = super().__new__(mcls, name, bases, namespace)
132+
def __new__(mcls, name, bases, namespace, **kwargs):
133+
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
134134
# Compute set of abstract method names
135135
abstracts = {name
136136
for name, value in namespace.items()

Lib/test/test_abc.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,5 +404,17 @@ class C(A, B):
404404
self.assertEqual(B.counter, 1)
405405

406406

407+
class TestABCWithInitSubclass(unittest.TestCase):
408+
def test_works_with_init_subclass(self):
409+
saved_kwargs = {}
410+
class ReceivesClassKwargs:
411+
def __init_subclass__(cls, **kwargs):
412+
super().__init_subclass__()
413+
saved_kwargs.update(kwargs)
414+
class Receiver(ReceivesClassKwargs, abc.ABC, x=1, y=2, z=3):
415+
pass
416+
self.assertEqual(saved_kwargs, dict(x=1, y=2, z=3))
417+
418+
407419
if __name__ == "__main__":
408420
unittest.main()

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,9 @@ Library
761761
- Issue #24142: Reading a corrupt config file left configparser in an
762762
invalid state. Original patch by Florian Höch.
763763

764+
- Issue #29581: ABCMeta.__new__ now accepts **kwargs, allowing abstract base
765+
classes to use keyword parameters in __init_subclass__. Patch by Nate Soares.
766+
764767
Windows
765768
-------
766769

0 commit comments

Comments
 (0)