P.R.F.
P.R.F.

Reputation: 33

How to determine the number of arguments passed to function?

I have a function that takes a variable number of arguments. I would like (in the function) get the number passed. The declaration looks like this:

def function(*args):

The function is called as follows:

function(arg1, arg2, ...)

Upvotes: 0

Views: 1340

Answers (2)

qiweunvjah
qiweunvjah

Reputation: 132

To get the number of parameters passed, you can use the signature module. Example:

from inspect import signature

def someMethod(self, arg1, kwarg1=None):
    pass

sig = (signature(someMethod))
print(len(list(sig.parameters)))

Output:

3

To get the names of the parameters, you do:

def someMethod(self, arg1, kwarg1=None):
    pass

sig = (signature(someMethod))
print(list(sig.parameters))

Read more here

Upvotes: 0

QQQ
QQQ

Reputation: 327

You can define the function as follows to get the values of the arguments:

def function(*args):
   for i in range(len(args)):
      print(args[i])

function(3, 5, 8)

Here is the result:

3
5
8

That is, args[i] receives the value of the i-th parameter passed to function.

Upvotes: 4

Related Questions