2

If I'm trying to overload an embedded Python function so that the second argument can be a long or an Object, is there a standard way to do it? Is this it?

What I'm trying now (names changed to protect the innocent):

  bool UseLongVar2 = true;
  if (!PyArg_ParseTuple(args, "ll:foo", &LongVar1, &LongVar2))
  {
      PyErr_Clear();
      if (!PyArg_ParseTuple(args, "lO&:foo", &LongVar1, convertObject, &Object))
      {
         UseLongVar2 = false;
         return NULL;
      }
  }

1 Answer 1

3

What I normally do is have two C functions that take the different arguments. The "python-facing" function's job is to parse out the arguments, call the appropriate C function, and build the return value if any.

This is pretty common when, for example, you want to allow both byte and Unicode strings.

Here is an example of what I mean.

// Silly example: get the length of a string, supporting Unicode and byte strings
static PyObject* getlen_py(PyObject *self, PyObject *args)
{
    // Unpack our argument (error handling omitted...)
    PyObject *arg = NULL;
    PyArg_UnpackTuple(args, "getlen", 1, 1, arg) ;

    if ( PyUnicode_Check(arg) )
    {
        // It's a Unicode string
        return PyInt_FromLong(getlen_w(PyUnicode_AS_UNICODE(arg))) ;
    }
    else
    {
        // It's a byte string
        return PyInt_FromLong(getlen_a(PyString_AS_STRING(arg))) ;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

How does that differ from what I'm doing here? After the example code I can say something along the lines of "result = UseLongVar2 ? fooLong(LongVar1, LongVar2) : fooObj(LongVar1, Object)"?
Just to clarify: I'm interested in how to tell which types of arguments were passed from Python. Is there something better than PyArg_ParseTuple, or is there a cleaner shorthand for separating out different types of variable. The construct I'm using would be completely hideous for even a few arguments that could have 2 or 3 possible types.
This is different because with your way, you're doing two tests. First the test to see if it passed, and then later you'll have to test the flags you set to see which arguments to parse. With the way I outlined, you only do one test. And no, I don't think that there's a cleaner way to check what args you got. Another good reason to keep the arguments in C extensions simple.
You didn't outline what structure you use to parse out the arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.