Skip to content

Support magic method init_subclass & class_getitem for extension class (PEP 487, 560) #3764

@KmolYuan

Description

@KmolYuan

#3518 supports to creating a generic Python class in Cython but extension class are still not available.
Same as the inheritance arguments support.

cdef class G:
    def __class_getitem__(cls, item):
        return cls

>>> G[int]
TypeError: __class_getitem__() takes exactly 1 positional argument (0 given)
cdef class G:
    def __class_getitem__(cls, *args):
        return cls

>>> G[int]
<class 'int'>

The generated code is incorrect:

static PyObject *xxx__class_getitem__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_cls, CYTHON_UNUSED PyObject *__pyx_v_item);

Solution

Explicitly add @classmethod for the magic methods. (but actually not required)

cdef class G:
    @classmethod
    def __init_subclass__(cls, a=None, **kwargs):
        super().__init_subclass__(**kwargs)
        print(a)

    @classmethod
    def __class_getitem__(cls, items):
        return cls

>>> G[int]
<class 'xxx.G'>
>>> class A(G[int], a=60): pass
60

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions