Home > Software design >  In the Python C API, if the second argument is not set how can I default to the value of the first?
In the Python C API, if the second argument is not set how can I default to the value of the first?

Time:09-23

I have an x, y parameters. Using the python C API, how can I default y to the value of x if y is None.

The python equivalent is:

def scale(x: float, y:Optional[float]=None):
    if y is None:
       y = x

    c_scale_api(x, y)

CodePudding user response:

just check it against Py_None.

static PyObject* scale(PyObject* self, PyObject* args) {
    PyObject* input2 = Py_None; // initialize to None
    double input1d, input2d;
    if (!PyArg_ParseTuple(args, "d|O", &input1d, &input2)) {
        return NULL;
    }
    if (input2 == Py_None)
    {
        input2d = input1d;
    }
    else 
    {
        input2d = PyFloat_AsDouble(input2);
    }
    return PyFloat_FromDouble(input2d);
}

this will return the value of the second argument for you to check.

  • Related