How to determine number of function/builtin/callable parameters programmatically?
<p>I want to be able to classify an unknown function/builtin/callable based on its number of arguments.</p>

<p>I may write a piece of code like that:</p>

<pre><code>if numberOfParameters(f) == 0:
    noParameters.append(f)
elif numberOfParameters(f) == 1:
    oneParameter.append(f)
else:
    manyParameters.append(f)
</code></pre>

<p>but I have no idea how to implement <code>numberOfParameters()</code>.  <code>inspect.getargspec</code> does not work with builtins. I can not use exceptions, since it is potentially expensive to call the function.</p>

<p>It would be great if the solution work with both Python 2.7 and Python 3.3+</p>

<p>You can somewhat do this, but only in Python 3. This is when <code>ArgumentClinic</code> made information about the signature of objects available.</p>

<p>Take note, not all built-ins are actually available as of right now, currently:</p>

<pre><code>__import__ vars max print dir __build_class__ min iter round getattr next 
</code></pre>

<p>do not expose information about their signature. For the rest <code>getargspec</code> (a thin wrapper around <code>getfullargspec</code>) and <code>Signature</code> would do.</p>

<p>In Python 2, you only have the option of <code>getargspec</code> which doesn't do the trick for built-ins and probably never will. So, there's no solution that spans across python versions. For the most compatible solution, I'd use <code>getargspec</code> as of right now.</p>

<p>As for the most simplistic way to check, just count the <code>args</code> from the <code>NamedTuple</code> returned:</p>

<pre><code>def NumberOfParameters(f):
    try:
        r = getargspec(f)
        return len(r.args)  # if it has kwargs, what do you do?
    except TypeError as e:
        print("Function {0} cannot be inspected".format(f.__name__))
</code></pre>

python python-2.7 function python-3.x callable