namedtuples in Cython?

1,205 views
Skip to first unread message

Chris Barker

unread,
Sep 20, 2012, 12:55:58 PM9/20/12
to cython...@googlegroups.com
I'm thinking of using namedtuples in Cython -- it seems a reasonable
way to wrap a c struct, and, at least in pure python, lighter weight
than a class.

If I'm going to do that, is seems I might as well use the C-API when
constructing, rather than doing it all with the Python API. But it
appears the namedtuple is written in pure python, as a subclass of
tuple.

Which I suppose means I need to create a nametuple class with the
Python call, but then I should be able to actually set the fields with
the C-API for a tuple.

But is there any point in this anyway -- is, in fact, a cdef class
just as lightweight (or maybe more lightweight) anyway?

-Chris





--

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception

Chris....@noaa.gov

Robert Bradshaw

unread,
Sep 20, 2012, 1:32:01 PM9/20/12
to cython...@googlegroups.com
On Thu, Sep 20, 2012 at 9:55 AM, Chris Barker <chris....@noaa.gov> wrote:
> I'm thinking of using namedtuples in Cython -- it seems a reasonable
> way to wrap a c struct, and, at least in pure python, lighter weight
> than a class.
>
> If I'm going to do that, is seems I might as well use the C-API when
> constructing, rather than doing it all with the Python API. But it
> appears the namedtuple is written in pure python, as a subclass of
> tuple.
>
> Which I suppose means I need to create a nametuple class with the
> Python call, but then I should be able to actually set the fields with
> the C-API for a tuple.
>
> But is there any point in this anyway -- is, in fact, a cdef class
> just as lightweight (or maybe more lightweight) anyway?

A cdef class is more lightweight, but requires an explicit class for
every set of names you want. (It also has the advantage of storing
members as C values, if you intend to use them a lot from your Cython
code.)

- Robert

Chris Barker

unread,
Sep 20, 2012, 4:05:46 PM9/20/12
to cython...@googlegroups.com
On Thu, Sep 20, 2012 at 10:32 AM, Robert Bradshaw <robe...@gmail.com> wrote:

> A cdef class is more lightweight,

Then that's the way to go, unless there is real reason for it to be a
tuple, too.

> but requires an explicit class for
> every set of names you want.

which namedtuple requires as well, you'd still create a specific
namedtuple class for each struct you wanted to wrap.

> (It also has the advantage of storing
> members as C values, if you intend to use them a lot from your Cython
> code.)

makes sense -- and it's mutable, which more closely follows the
use-cases of C structs.

namedtuples area also sequences, but I suppose you could add that to
your cdef class if you wanted to.

Thanks -- I see now why this hasn't been done -- really no point.
Reply all
Reply to author
Forward
0 new messages