Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count positional arguments in function signature

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.

like image 837
BramAppel Avatar asked Sep 11 '19 09:09

BramAppel


People also ask

What is a parameter in a function signature?

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.

What is the signature of the function func?

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.

What is the signature of a python function?

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.

What is positional argument in Python?

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.


1 Answers

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, or None if no arguments have a default value.

and:

co_argcount is the number of positional arguments (including arguments with default values);

like image 187
MrGeek Avatar answered Oct 21 '22 22:10

MrGeek