C Extension question-> How handle lists and tuples as arguments?

  • Thread starter Christian Seberino
  • Start date
C

Christian Seberino

Py_ParseTuple is a great C function to set C variables from
Python objects in a C extension.

Usage is straight forward for integers and strings but I'm wondering
what to do if I ever want to send in a list or tuple.

First problem is that we don't know the LENGTH of the list/tuple.

Second problem is we don't know the TYPES of the elements.

Chris
 
?

=?ISO-8859-1?Q?Gerhard_H=E4ring?=

Christian said:
Py_ParseTuple is a great C function to set C variables from
Python objects in a C extension.

Usage is straight forward for integers and strings but I'm wondering
what to do if I ever want to send in a list or tuple.

First problem is that we don't know the LENGTH of the list/tuple.

Second problem is we don't know the TYPES of the elements.

I don't understand your problem. For "other" parameters, use "O" as
format character in ParseTuple...(). Then if you need to check if the
passed parameter is a sequence (either tuple or list), you can just use
PySequenceCheck().

For the rest, use the functions for the sequence protocol, like
PySequence_Length() and the like.

HTH,

-- Gerhard
 
M

Martin v. =?iso-8859-15?q?L=F6wis?=

Py_ParseTuple is a great C function to set C variables from
Python objects in a C extension.

I disagree. It is much better to use specific functions.
Usage is straight forward for integers and strings but I'm wondering
what to do if I ever want to send in a list or tuple.

First problem is that we don't know the LENGTH of the list/tuple.

Second problem is we don't know the TYPES of the elements.

Just like you would do it in Python:

len(x) --> PyObject_Length(x)
x --> PySequence_GetItem(x, i) (assuming x is a sequence)
isinstance(o, int) --> PyInt_Check(o)
obtain native value --> PyInt_AsLong(o)

HTH,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top