Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check the number of parameters passed in Python function

I'm new in Python and wants to know if there is a simple way to get amount of passed parameters in Python function.

a(1, 2, 3) ==>3
a(1, 2) ==>2
like image 847
JasmineOT Avatar asked Oct 12 '15 05:10

JasmineOT


People also ask

How do you find the number of parameters passed to a function?

To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you.

How do you check the number of inputs in Python?

Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work.


2 Answers

def a(*args, **kwargs):
  print(len(args) + len(kwargs))
like image 59
Ignacio Vazquez-Abrams Avatar answered Oct 19 '22 23:10

Ignacio Vazquez-Abrams


You can do this by using locals()

It is important to note, that this should be done as ultimately, your first step in your method. If you introduce a new variable in your method, you will change your results. So make sure you follow it this way:

def a(a, b, c):
    # make this your first statement
    print(len(locals()))

If you did this:

def a(a, b, c):
    z = 5
    print(len(locals()))

You would end up getting 4, which would not be right for your expected results.

Documentation on locals()

like image 36
idjaw Avatar answered Oct 20 '22 01:10

idjaw