[Numpy-discussion] Access dtype kind from cython

Nathaniel Smith njs at pobox.com
Thu Jan 1 17:16:34 EST 2015


On Thu, Jan 1, 2015 at 7:38 PM, Valentin Haenel <valentin at haenel.co> wrote:
[...]
> So, I actually discovered an additional ugly workaround. Basically it
> turns out, that my dtype instance does have a 'kind' attribute, but it
> is a Python str object. Hence I needed to do:
>
>   ord(dtype_.kind[0])

Your Cython dtype object is simultaneously a C and Python object -- if
you ask for a C-level attribute that Cython knows about, then it'll
access the C struct field directly; if you ask for anything else, then
it'll do a normal Python attribute lookup.

> To cast it to a Cython char... This is because---for reasons I don't
> understand---when you define a char in cython and you try to assign a
> python object to it, that object needs to be an integer. Otherwise you
> get:
>
>   TypeError: an integer is required
>
> During run-time.

This is because in C, char is the name for an integer type. It was the
70s, they didn't know any better...

> Using the hack above my code now compiles and the tests all pass. I
> would guess that it probably won't perform very well due to various
> python to c back and forth activities.

Eh, there's an excellent chance that it won't matter. Usually this
kidn of thing only matters if you're accessing the field from inside a
tight inner loop that gets called thousands of times per second. This
is one of the nice things about Cython: you can be lazy and write
ordinary Python code everywhere outside those loops, as compared to
regular extension modules where you have to laboriously write
everything in C, even the parts that aren't speed critical.

-n

-- 
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org



More information about the NumPy-Discussion mailing list