Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

KmolYuan opened this issue Aug 3, 2020 · 1 comment


Copy link

KmolYuan commented Aug 3, 2020

#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);


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

cdef class G:
    def __init_subclass__(cls, a=None, **kwargs):

    def __class_getitem__(cls, items):
        return cls

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

da-woods commented Aug 3, 2020

__init_subclass__ looks like a bit of a nightmare for cdef class - it'd probably work when you base a regular class from it, but basing another cdef class off I don't see how it could work. I'd be inclined to have Cython raise an error if you create __init_subclass__ for a cdef class rather than try to work around that inconsistency.

__class_getitem__ should probably work. PR welcome I suspect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet

No branches or pull requests

3 participants