简体   繁体   中英

Count the number of arguments actually passed to a python function

I would like to retrieve the number of arguments that have been passed to a Python function. In fact I am writting a Matlab code in Python and in Matlab, the code line is:

if (nargin > 2)
    ...
end

I would like to do the same thing in Python with a function that have this form: def my_func(a,b,c=3,d=4, ...):

When calling it, I would be able to retrieve the number of passed arguments, for instance:

my_func(1,2) would return 2

my_func(1,2,3) would return 3

my_func(1,2,3,4) would return 4 etc.

I have seen some topics but only giving the number of arguments and description of the function, and not the number of arguments passed when calling it in a script.

I hope that I am clear in explaining my issue.

Best regards, MOCHON Rémi

Below code will work for you

def param_count(*args):
    return len(args)

Not exactly what you ask for, but a simple way to achieve this is to count the number of args and kwargs using a decorator, and then pass it to the function.

The decorator will look like this:

def count_nargin(func):
    def inner(*args, **kwargs):
        nargin = len(args) + len(kwargs)
        return func(*args, **kwargs, nargin=nargin)
    return inner

You will then have to modify your function to accept the nargin parameter:

@count_nargin
def my_func(a,b,c=3,d=4,nargin=None):
    print(nargin)

For example, calling the above function returns:

>>> my_func(1,2)
2

>>> my_func(1,2,3)
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM