Setting cdef variables from PyObject properties en masse

25 views
Skip to first unread message

Serdar Yegulalp

unread,
Dec 27, 2016, 12:27:45 AM12/27/16
to cython-users
I have functions that take in an Python object and set the various properties to typed equivalents, e.g.:

cdef int x = pyobject.x, y=pyobject.y, z=pyobject.z

This is done to allow any future manipulations of the variable to be done as purely in C as possible.

Is there a more efficient way to set a whole slew of these at once, rather than using the construction shown above?

Robert Bradshaw

unread,
Dec 28, 2016, 12:00:12 AM12/28/16
to cython...@googlegroups.com
I might write it in multiple lines to be clearer, e.g. 

cdef int x, y, z
x, y, z = pyobject.x, pyobject.y, pyobject.z

You could alternatively fore pyobject to be a Python object, or write a struct that has the relevant members and write helpers that did the unpacking (and packing if need be), e.g.

cdef struct c_members_struct:
    int x
    int y
    int z

cdef [inline] c_members_struct extract_c_members(pyobject):
    cdef c_members_struct c_members
    c_members.x = pyobject.x
    c_members.y = pyobject.y
    c_members.z = pyobject.z
    return c_members

or, if the attributes happen to align exactly, 

cdef c_members_struct c_members = pyobject.__dict__

You should also look at whether all members need to be in C variables, or only a couple accesses dominate the computation. Profile, profile, profile. 

- Robert



Reply all
Reply to author
Forward
0 new messages