2

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

1
  • I don't think that is possible. Although this approach might work for some cases - put a check explicitly in your code that how many values received are exactly equal to the default values specified :) Commented May 3, 2021 at 13:12

2 Answers 2

2

Below code will work for you

def param_count(*args):
    return len(args)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.