How can I write a C function that takes either an int or a float?
<p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>

<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only float.</p>

<p>How can I make my function allow inputs that are either ints or floats?</p>

<p>I'm wondering if I should just take the input and put it into a PyObject and somehow take the type of the PyObject - is that the right approach?</p>

<p>You can check type of input value like this:</p>

<pre><code>    PyObject* check_type(PyObject*self, PyObject*args) {
    PyObject*any;

    if (!PyArg_ParseTuple(args, "O", &amp;any)) {
        PyErr_SetString(PyExc_TypeError, "Nope.");
        return NULL;
    }

    if (PyFloat_Check(any)) {
        printf("indeed float");
    }
    else {
        printf("\nint\n");
    }

    Py_INCREF(Py_None);

    return Py_None;
}
</code></pre>

<p>You can extract float value from object using: </p>

<pre><code>double result=PyFloat_AsDouble(any);
</code></pre>

<p>But in this particular situation probably no need to do this, no matter what you parsing int or float you can grab it as a float and check on roundness: </p>

<pre><code>    float target;
    if (!PyArg_ParseTuple(args, "f", &amp;target)) {
                PyErr_SetString(PyExc_TypeError, "Nope.");
                return NULL;
    }

    if (target - (int)target) {
        printf("\n input is float \n");
    }
    else {
        printf("\n input is int \n");
    }
</code></pre>

python c python-extensions