Sub topic 5
Passing keyword arguments in the class line
This chapter assumes you can write classes with inheritance, call super(), and use **kwargs. You should also have read the previous chapter on __init_subclass__.
Keywords in the class line
The parentheses of a class statement accept more than base classes. You can add keyword arguments after the bases:
class Child(Base, tag='alpha'):
passYou have already seen one such keyword, metaclass=. Any other keyword is passed along to the class-creation machinery. Python forwards it to __prepare__, to the metaclass's __new__ and __init__, and, through type.__new__, to the parent's __init_subclass__.
Receiving keywords in `__init_subclass__`
With no custom metaclass, the keywords reach __init_subclass__ on the parent. Declare the ones you understand and forward the rest:
class Base:
def __init_subclass__(cls, /, *, tag='default', **kwargs):
super().__init_subclass__(**kwargs)
cls.tag = tag
class A(Base, tag='alpha'):
pass
class B(A):
pass
print(A.tag) # alpha
print(B.tag) # defaultB.tag is 'default', not 'alpha'. Python calls __init_subclass__ again for B, and B's class line has no tag. The keywords are not inherited. If you want a subclass to keep its parent's value, look it up yourself:
class Base:
tag = 'default'
def __init_subclass__(cls, /, *, tag=None, **kwargs):
super().__init_subclass__(**kwargs)
if tag is not None:
cls.tag = tagNow B.tag resolves through normal attribute lookup to A.tag.
Why you must call `super().__init_subclass__(**kwargs)`
The last class in the chain is object. Its __init_subclass__ accepts no keywords and raises TypeError if it receives any. Forwarding **kwargs has two effects:
- A misspelled or unknown keyword fails loudly instead of being ignored.
- Other classes in a multiple-inheritance hierarchy get a chance to consume their own keywords.
class Base:
def __init_subclass__(cls, /, *, tag='default', **kwargs):
super().__init_subclass__(**kwargs)
cls.tag = tag
try:
class C(Base, colour='red'):
pass
except TypeError:
print('unknown keyword rejected') # unknown keyword rejectedIf you swallowed **kwargs instead of forwarding it, colour='red' would pass silently.
Keywords with a metaclass
A custom metaclass sees the keywords before __init_subclass__ does. Its __new__ must pass the keywords it does not consume to super().__new__, and __init__ receives them too:
class Meta(type):
def __new__(mcls, name, bases, namespace, *, version=1, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
cls.version = version
return cls
def __init__(cls, name, bases, namespace, *, version=1, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
class Model(metaclass=Meta, version=3):
pass
print(Model.version) # 3Both methods declare version, so it never reaches __init_subclass__. If __init__ omitted version, it would land in **kwargs and be passed to type.__init__. That is harmless, because type.__init__ ignores extra keywords. type.__new__ is stricter, because it forwards keywords to __init_subclass__.
Summary of the receivers
| Receiver | Signature carries keywords? | Unknown keywords |
|---|---|---|
| `metaclass.__prepare__` | Yes | `type.__prepare__` ignores them |
| `metaclass.__new__` | Yes | Forwarded to `__init_subclass__` by `type.__new__` |
| `metaclass.__init__` | Yes | `type.__init__` ignores them |
| `Base.__init_subclass__` | Yes | `object.__init_subclass__` raises `TypeError` |
Common errors
- Forgetting
**kwargsin a metaclass__new__. Any keyword in the class line then raisesTypeErrorfor an unexpected argument. - Forgetting to forward
**kwargstosuper().__new__. Keywords meant for a parent's__init_subclass__are then dropped. - Expecting keywords to inherit. They apply only to the class whose line contains them.
- Omitting
/afterclsin__init_subclass__. This is only a problem if a subclass passes a keyword namedcls.
Exercise
Given class Base: def __init_subclass__(cls, /, *, tag='x', **kwargs): super().__init_subclass__(**kwargs); cls.tag = tag, what do class A(Base, tag='y'): pass and class B(A): pass give for A.tag and B.tag, and why?
Show answer
A.tag is 'y' and B.tag is 'x'. Python calls Base.__init_subclass__ separately for each subclass. B's class line has no tag, so the default 'x' is used and sets B.tag directly.
Exercise
A class line passes colour='red' to a parent whose __init_subclass__ accepts only tag and **kwargs, and it calls super().__init_subclass__(**kwargs). What happens, and what happens if the super() call is removed?
Show answer
With the super() call, colour reaches object.__init_subclass__, which raises TypeError. Without the call, colour is silently ignored, so typos go unnoticed and other classes in the chain never see their keywords.