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

Closed
KmolYuan opened this issue Aug 3, 2020 · 1 comment

Comments

@KmolYuan
Copy link
Contributor

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

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
@da-woods
Copy link
Contributor

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
Projects
None yet
Development

No branches or pull requests

3 participants