Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class "keyword arguments" in Python 3

I noticed this from the docstring of __build_class__:

__build_class__(func, name, *bases, metaclass=None, **kwds) -> class

Internal helper function used by the class statement.

The part that intrigued me was the **kwds part. Can class definitions take keyword arguments? I tried it, but I got a very strange error:

>>> class Test(a=1):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments

What's the deal here? Can classes in Python 3 somehow accept keyword arguments? Maybe a special metaclass is required?

like image 637
asmeurer Avatar asked Oct 24 '25 22:10

asmeurer


1 Answers

Can classes in Python 3 somehow accept keyword arguments?

Yes. Any keyword arguments in the class statement besides metaclass are passed to the metaclass. If the metaclass argument is specified, it's used as the metaclass; otherwise, the metaclass is type. See PEP 3115 for more details.

like image 119
user2357112 supports Monica Avatar answered Oct 26 '25 12:10

user2357112 supports Monica