Using PyArg_ParseTuple to with optional fields.

DL Neil PythonList at
Thu Feb 28 13:36:25 EST 2019


On 28/02/19 10:18 PM, Anthony Flury via Python-list wrote:
> I am trying to write an extension module with a function (actually an 
> __init__ method, but I am not sure that matters) where the function can 
> be called as either :
>      my_func()
> or
>      my_func( a, b, c, d) - where a,b,c,d are all doubles.
> I would prefer not to allow the function to be called with some 
> arguments specified - it is either all four - or none.

Perhaps it does matter - __init__() only ever returns None, which 
may/not be of-concern at the 'top end'.

During the last few days, either 'here' or over on Python-Tutor, there 
has been a discussion about alternate ways to instantiate an object, ie 
with different numbers of arguments.

> I have tried the following format strings to PyArg_ParseTuple :
>   * "dddd" - but this a mandatory 4 doubles - doesn't allow for the no
...> Can I do what I want with a single call to PyArg_ParseTuple  ?

+1 for using provided (and optimised) standard facilities!

What advantages does PyArg provide? Has its use become 'blinkers' - a 
straight-jacket to your thinking?

If the data is coming from outside Python directly, is it not possible 
to use named-keyword arguments, ie pick-up the 'optional' 
auto-magically? Somewhere in the existing code there's probably already 
some coding for the 'empty args' option, inserting default values...

How about *args (or *kwargs)? Remember that the "args" (sans asterisk) 
becomes a tuple inside the method. It can be empty or filled. That 
leaves you with two tests: len() zero or four, and (optionally) a loop 
to check that the four arg-tuple elements are all() floats.

Regards =dn

More information about the Python-list mailing list