| Extending & Embedding Python Using C - Arguments |
| Written by Mike James | |||||
| Tuesday, 03 February 2026 | |||||
Page 4 of 4
SequencesDealing with more complex Python objects requires more than format specifiers. However, if an object is a sequence then you can extract the data it contains. A sequence is a “container” for a range of other, usually simpler, data types so that they can be accessed by an integer index. If you want to know more about this see Programmer’s Python: Everything is Data, ISBN: 9781871962757. You cannot use a format to convert a sequence into something equivalent in C such as a struct or an array, but you can convert each of the elements in the sequence – providing they are simple. If you enclose format specifiers in parentheses then it is assumed that the items are derived from a sequence. For example: (dis) means that the first element is a double, next an integer and next a string. This would unpack a tuple or a list or any sequence into three C variables of the correct type. You can also nest parentheses to handle elements which are themselves sequences. For example: (d(ii)) means that the first element is a double and the second is a sequence with a pair of integers e.g. (3.14,(1,2)). For example, if we have a sequence that has an integer first element followed by a pair of doubles and then a string we can unpack this into C variables using: static PyObject *sequenceElements(PyObject *self, If you call this using: import example example.sequenceElements((2,1.2,1.3,"test")) then you will see displayed: 2 1.200000 1.300000 test If you replace the tuple with a list then it still works. If the two doubles are formed into a tuple then we can still extract them by changing the format to: if (!PyArg_ParseTuple(args, "(i(dd)s)", &number, With this change you can call the function using: import example example.sequenceElements((2,(1.2,1.3),"test")) The types of the C variables have to match the format specifier and this means that if the sequence you pass in doesn’t match the format you will generate a TypeError exception. While this is a way of getting lists and tuples into your C function, notice that it only works for “short” sequences because you have to create a C variable for each item. If you want to convert a list or tuple with an arbitrary number of elements you are going to have to do the job yourself. A complete listing of all of the functions given in this chapter, together with test Python code, can be found on the book’s webpage at www.iopress.info. Summary
Extending & Embedding Python Using CBy Mike JamesBuy from Amazon. ContentsPreface
<ASIN:B0CK3X93KF> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
|||||
| Last Updated ( Tuesday, 03 February 2026 ) |


