4

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see. Assumedly this was just implemented for the sake of the new metaclass= syntax, since I think the same thing should be possible by just using a metaclass factory, like class MyClass(metaclass=get_metaclass(**kwargs)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.