2

My script reads data from CSV-files and passes the rows to C code, which uses PyArg_ParseTuple() and/or PyArg_ParseTupleAndKeywords() to parse the arguments and then work on them.

Some of the arguments are supposed to be strings, others -- numbers (integers and floating point). The expected types are passed to the PyArg-functions:

if (!PyArg_ParseTupleAndKeywords(args, kw, "sdddd", keywords,
    &name, &height, &width, &depth, &weight))
    return NULL;

Trouble is, all of the fields parsed from CSV are strings. When passed to PyArg_ParseTupleAndKeywords this triggers a type error because "11" is not a number, even if 11 is...

So I'm explicitly casting some fields to numbers, but that looks ugly and duplicates the knowledge already expressed in the format string.

Is there a way to tell the PyArg-functions to try to convert the objects into numbers, when necessary -- when the specified argument is supposed to be a number -- and only fail the parsing, if the conversion fails?

5
  • 4
    In the tagged C you can't cast a string to a numeric value. You either use a library function to convert it, or DIY with Horner. Commented Oct 7 at 19:57
  • 1
    Can you provide more information? Like how are you calling this from python? And at least an example of the csv. Try to create a minimal reproducible example. Commented Oct 8 at 0:12
  • As @WeatherVane says. See the linked duplicate for the C API way to do it once you've already received the string in the C code. Commented Oct 8 at 3:35
  • This is not a duplicate at all. I know, how to perform a conversion -- I was just hoping, the PyArg functions can perform the conversion for me... Commented Oct 8 at 4:00
  • @MikhailT: You could write your own function to use with the O code for the parse function, but that's it. Commented Oct 8 at 11:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.