Class annotation in pure python mode in .pxd file

19 views
Skip to first unread message

Shirzart Enwer

unread,
Oct 18, 2022, 2:12:11 PM10/18/22
to cython-users
I have a class like this in vector.py file

class Vector:
    value
    def __init__(self, x: float, y:float, z:float):
        self.value = np.array([x, y, z])
   
    @classmethod
    def from_np_Array(cls, array: np.ndarray):
        self.value = array
    
    def scale(self, factor: float):
        return Vector(...)




How do I annotate in .pxd file for the class method?
My current .pxd fie looks like this:

cdef class Vector:
    cdef public double[:] value  
# How do I annotate the 'x', 'y', 'z', which pass to the '__init__' ?

    cpdef Vector from_np_Array(cls, double[:] array)   
# Is this correct? can I write `cls` here?
    
    cpdef Vector scale(double[:])  
# Is this also correct, in the case when I return a new class instance?

Thanks a lot!


da-woods

unread,
Oct 21, 2022, 1:35:19 PM10/21/22
to cython...@googlegroups.com
That looks broadly right although I haven't actually tried to run it.

> # How do I annotate the 'x', 'y', 'z', which pass to the '__init__' ?

I actually wouldn't. You pass them straight to a Numpy array so it'd be a pessimization to convert them to then from a C floating point type.

> # Is this correct? can I write `cls` here?

I don't think that a cpdef classmethod is supported. Your options are
1. make it a staticmethod instead (I think you'd need to put the staticmethod decorator in the pxd file)
2. don't bother with cpdef and just make it a regular classmethod. I'm not a big fan of cpdef anyway. `cls` is fine though - it's just a variable name.

The other thing you could do is skip the pxd and use the annotations in the py file to define the type. Use `@cython.cclass` as a decorator on the class. `x: float` will be understood by Cython anyway to be a C double. If you have types taking a memoryview then write it as `array: cython.double[:]` instead of `np.ndarray`.

Hopefully some of that is useful.

David
--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cython-users/82eac098-339f-47b0-93b2-8b9c5d1dbeb9n%40googlegroups.com.


Reply all
Reply to author
Forward
0 new messages