Sub topic 5
Passing keyword arguments in the class line
This chapter assumes you can define classes and use inheritance, call super(), and write functions that take **kwargs. It also assumes you know the earlier chapter's __init_subclass__ hook, which runs on a parent class each time a subclass is defined. Here you will see how the extra keyword arguments in a class line reach that hook and the metaclass hooks, and where they get lost.
What the class line accepts
A class statement can carry keyword arguments after the base classes:
class Child(Base, metaclass=Meta, color="red", size=3):
passPython handles these in a fixed way:
- It removes
metaclass=from the keywords and uses it to choose the metaclass. If you don't give one, it usestypeor the metaclass of the bases. - It passes every remaining keyword (
colorandsizehere) to the metaclass's__prepare__. - It passes the same keywords to the metaclass call, so they reach
__new__and__init__. type.__new__then forwards them to__init_subclass__on the parent class.
Nothing stores these keywords on the class. Each hook receives them once, at creation time, and they are gone afterwards unless a hook saves them.
Receiving keywords in `__init_subclass__`
For most code, __init_subclass__ is the only place that needs to read class keywords. Declare the keywords you want as parameters and take the rest with **kwargs.
class Endpoint:
routes = {}
def __init_subclass__(cls, /, *, path, method="GET", **kwargs):
super().__init_subclass__(**kwargs)
if not path.startswith("/"):
raise ValueError(f"path must start with '/': {path!r}")
cls.path = path
cls.method = method
Endpoint.routes[(method, path)] = cls
class ListUsers(Endpoint, path="/users"):
pass
class CreateUser(Endpoint, path="/users", method="POST"):
pass
print(sorted(Endpoint.routes))
# [('GET', '/users'), ('POST', '/users')]
try:
class Broken(Endpoint):
pass
except TypeError as exc:
print("missing keyword:", type(exc).__name__)The parameter list cls, /, *, path, method="GET" does three things:
- The
/makesclspositional-only, so a class keyword namedclscannot collide with it. - The
*makespathandmethodkeyword-only, which matches how callers write them. pathhas no default, so leaving it out fails at class-definition time with aTypeError. The error appears when the module is imported, not when the code first uses the class.
A required keyword also applies to every subclass, including intermediate abstract ones. If you want abstract bases, give the keyword a default of None and check it where it matters.
Forwarding the rest with `super()`
Always call super().__init_subclass__(**kwargs) and pass on the keywords you did not consume. At the end of the chain is object.__init_subclass__, which accepts no keywords. It acts as the typo detector:
try:
class Typo(Endpoint, path="/x", metod="POST"):
pass
except TypeError as exc:
print(type(exc).__name__) # TypeErrormetod is not a parameter of Endpoint.__init_subclass__, so it lands in kwargs. It travels to object.__init_subclass__, which raises. If you swallowed **kwargs without forwarding it, the typo would pass silently.
Forwarding also lets several base classes each take their own keywords. Python calls __init_subclass__ through the method resolution order, so each class in the chain removes what it understands:
class Tagged:
def __init_subclass__(cls, /, tag=None, **kwargs):
super().__init_subclass__(**kwargs)
cls.tag = tag
class Named:
def __init_subclass__(cls, /, label=None, **kwargs):
super().__init_subclass__(**kwargs)
cls.label = label
class Item(Tagged, Named, tag="sale", label="Blue mug"):
pass
print(Item.tag, Item.label) # sale Blue mugTagged receives both keywords, keeps tag, and forwards label to Named. Named keeps label and forwards an empty set to object. This only works because both classes call super(). If Tagged forgot to forward, Named would never run and Item.label would not exist.
Keywords are not inherited
The keywords apply only to the class whose class line contains them. A grandchild does not repeat them automatically. With the required path above, this fails:
try:
class AdminListUsers(ListUsers):
pass
except TypeError as exc:
print("must repeat path:", type(exc).__name__)Python calls Endpoint.__init_subclass__ again for AdminListUsers, and this time no path arrives. If you want children to inherit a value, store it on the class and treat the keyword as an optional override:
class Route:
path = None
method = "GET"
def __init_subclass__(cls, /, path=None, method=None, **kwargs):
super().__init_subclass__(**kwargs)
if path is not None:
cls.path = path
if method is not None:
cls.method = method
class Users(Route, path="/users"):
pass
class UserWrite(Users, method="POST"):
pass
print(UserWrite.path, UserWrite.method) # /users POSTUserWrite passes only method. path is None in the call, so the class attribute inherited from Users stays in place. Using None as "not given" is the usual convention. Use a private sentinel object instead if None is a valid value for the keyword.
Keywords with a metaclass
When a metaclass is involved, the keywords reach more places, and each place must accept them. This diagram follows one class statement.
A metaclass can take its own keywords and still let __init_subclass__ have theirs:
class Meta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
print("prepare", name, kwargs)
return super().__prepare__(name, bases, **kwargs)
def __new__(mcls, name, bases, ns, *, version=1, **kwargs):
cls = super().__new__(mcls, name, bases, ns, **kwargs)
cls.version = version
return cls
def __init__(cls, name, bases, ns, *, version=1, **kwargs):
super().__init__(name, bases, ns, **kwargs)
class Base(metaclass=Meta):
def __init_subclass__(cls, /, flag=False, **kwargs):
super().__init_subclass__(**kwargs)
cls.flag = flag
class Doc(Base, version=3, flag=True):
pass
print(Doc.version, Doc.flag) # 3 TrueRunning this prints prepare Base {} and prepare Doc {'version': 3, 'flag': True} before the final line. Four points matter:
__prepare__sees every keyword, including ones it does not use. It must accept**kwargsor class creation fails.Meta.__new__takesversionout of the keywords before callingtype.__new__. If it passedversionon, the chain would end atBase.__init_subclass__, thenobject.__init_subclass__, which rejects it.Meta.__init__must also accept the keywords, because Python calls it with the same arguments as__new__. The built-intype.__init__ignores keyword arguments, so forwarding**kwargsto it is safe.flagis not mentioned inMetaat all. It passes through**kwargstotype.__new__, which delivers it toBase.__init_subclass__.
Common problems
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: ... takes no keyword arguments` | A keyword reached `object.__init_subclass__` because no class consumed it, often a typo | Check the keyword name, or add a parameter for it |
| A second base class's keyword has no effect | An earlier `__init_subclass__` did not call `super().__init_subclass__(**kwargs)` | Forward `**kwargs` in every hook |
| Grandchild fails with a missing keyword | Keywords apply only to the class named in that `class` line | Make the keyword optional and store the value on the class |
| `__prepare__() got an unexpected keyword argument` | A custom `__prepare__` lacks `**kwargs` | Accept and forward `**kwargs` |
| Keyword consumed by the metaclass also reaches `__init_subclass__` | `__new__` passed it on to `type.__new__` | Declare it as a named parameter and do not forward it |
| A class keyword named `cls` raises `TypeError` | `cls` is a normal parameter and collides with the first argument | Declare `cls, /` to make it positional-only |
Design guidance
Class keywords work well for per-class configuration that is set once and read many times, such as a table name, a route, or a plugin key. They keep the setting next to the class name, where readers see it first. They are less suitable for values that need computing from the class body, because the body has not run when the keywords are evaluated. Use a class attribute or a decorator for those.
Prefer __init_subclass__ for consuming keywords. Reach for a metaclass keyword only when the metaclass itself must change behaviour based on it, for example when __prepare__ needs to choose the namespace type.
Exercise
What happens when you run class X(Endpoint, path="/x", metod="POST") with the Endpoint class from this chapter, and why?
Show answer
It raises a TypeError when the class is defined. Endpoint.__init_subclass__ consumes path, and metod stays in kwargs. The method forwards kwargs to super().__init_subclass__, and object.__init_subclass__ rejects any keyword, so the misspelling is reported instead of ignored.
Exercise
A Meta.__new__ is defined as def __new__(mcls, name, bases, ns, *, version=1, **kwargs) and ends with return super().__new__(mcls, name, bases, ns, version=version, **kwargs). A class Doc(Base, version=3) fails. Why, and how do you fix it?
Show answer
Passing version=version forwards the keyword to type.__new__, which forwards it to the parent's __init_subclass__. If no class in that chain accepts version, object.__init_subclass__ raises TypeError. Remove version=version from the super().__new__ call and set cls.version = version on the created class instead, as the chapter's Meta does.
Exercise
You write class Grandchild(Users) where Users was defined as class Users(Route, path="/users") and Route.__init_subclass__ has path=None as default. What is Grandchild.path, and why?
Show answer
It is "/users". The path keyword is None for Grandchild, so __init_subclass__ leaves the attribute alone, and Grandchild inherits path from Users through normal attribute lookup.