I have the following function signature:
# my signature
def myfunction(x, s, c=None, d=None):
# some irrelevant function body
I need the number of positional arguments. How can I return the number (2) of positional arguments (x & s). The number of keyword arguments is not relevant.
The function func (above) has the signature (a, b, c) . We know that it requires three arguments, one for a, b and c . These ( a, b and c) are called parameters. The parameter is the atomic unit of a signature . Every parameter has at a minimum a name and a kind.
The function func (above) has the signature (a, b, c) . We know that it requires three arguments, one for a, b and c . These ( a, b and c) are called parameters.
Python callables have a signature: the interface which describes what arguments are accepted and (optionally) what kind of value is returned. The function func (above) has the signature (a, b, c) . We know that it requires three arguments, one for a, b and c . These ( a, b and c) are called parameters.
Also, we are going to take a peek at keyword arguments to make an important point about arguments in Python. Positional argument means that the argument must be provided in a correct position in a function call.
You can get the number of all arguments (using f.__code__.co_argcount
), the number of keyword arguments (using f.__defaults__
), and subtract the latter from the first:
def myfunction(x, s, c=None, d=None):
pass
all_args = myfunction.__code__.co_argcount
if myfunction.__defaults__ is not None: # in case there are no kwargs
kwargs = len(myfunction.__defaults__)
else:
kwargs = 0
print(all_args - kwargs)
Output:
2
From the Docs:
__defaults__
: A tuple containing default argument values for those arguments that have defaults, orNone
if no arguments have a default value.
and:
co_argcount
is the number of positional arguments (including arguments with default values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With