1

How to use the Python C-API for the Complex class (documented here) to:

  1. convert a general PyObject (which might be a String, Long, Float, Complex) into a Complex PyObject?
  2. convert a Complex PyObject into String PyObject?

Python has a complex() function, documented here):

Return a complex number with the value real + imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long() and float(). If both arguments are omitted, returns 0j.

However, it isn't obvious which API function (if any) is backing it.

It would appear none of them, is the above paragraph talks about two PyObject* parameters, and none of the API functions listed match that signature.

1 Answer 1

1

When in doubt, do what Python does: call the constructor.

PyObject *c1 = PyObject_CallFunction(PyComplex_Type, "s", "1+2j");
If (!c1)
  return NULL;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for PyObject_CallFunction, this way of using the API opens up some interesting possibilities! Is there any way of converting an arbitrary PyObject* to a complex type?
@Pi: You probably want PyObject_CallFunctionObjArgs() for that.
I notice PyComplex_Type is a PyTypeObject, whereas signatures specify a PyObject*. Wouldn't I need reinterpret_cast<PyObject*>(&PyTypeObject) or something similarly nasty?
@Pi: "Type objects can be handled using any of the PyObject_*() [...] functions" So some sort of casting may be required, but it shouldn't kill the interpreter.

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.