Why is the cls keyword attribute reserved when using typing.Generic in python?

Viewed 94

How is it that the Generic class (I'll be using Python 3.7+ PEP-0560), restricts the use of cls as a keyword argument in __init__ ?

This is pretty clear:

>>> from typing import Generic, TypeVar
>>> I = TypeVar("I")
>>> class A(Generic[I]):
...     def __init__(self, cls=1):
...         pass
... 
>>> A(1)  # No error
>>> A(cls=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() got multiple values for argument 'cls'

This looks like something specific to Generic. Thanks

1 Answers

According to the source code:

    def __new__(cls, *args, **kwds):
        if cls in (Generic, Protocol):
            raise TypeError(f"Type {cls.__name__} cannot be instantiated; "
                            "it can be used only as a base class")
        if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
            obj = super().__new__(cls)
        else:
            obj = super().__new__(cls, *args, **kwds)
        return obj

Here we can see it uses cls as the name, so you cannot pass another one in the **kwds.

Related