17

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
JasmineOT
  • 1,978
  • 2
  • 20
  • 30
  • Possible duplicate of [Getting list of parameter names inside python function](http://stackoverflow.com/questions/582056/getting-list-of-parameter-names-inside-python-function) – TigerhawkT3 Oct 12 '15 at 05:40
  • Another possibility [here](http://stackoverflow.com/questions/218616/getting-method-parameter-names-in-python). – TigerhawkT3 Oct 12 '15 at 05:40
  • And I might as well say this is an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Oct 12 '15 at 05:41

3 Answers3

28
def a(*args, **kwargs):
  print(len(args) + len(kwargs))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 3
    I'm giving +1 to this anwer, because argument counting inside a function does make sense only when there are variable amount of them. – VPfB Oct 12 '15 at 05:57
15

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()

idjaw
  • 25,487
  • 7
  • 64
  • 83
1

you could also change the input for your function to a list, so to have a function:

a(your_list)

then to know how many arguments have been passed to the function, you could simply do:

print len(your_list)

However, this means that you change the input type for your function, from many input variables to only one, the list(which can have a variable number of elements).

Helios83
  • 87
  • 1
  • 12