Search code examples
pythonfunctionargumentsdecoratorcounting

How to count the number of variables in a function - Python


I want to be able to write a function that counts the number of arguments in a function, for example:

counter("one", "two")

2

counter("one", "two", "three")

3

etc,

I have this so far but I'm not sure it's right. Could someone help me out with this please? Thanks.

def counter(f):
    f.counter = 0
    def counting_f(*args):
        v = f(*args)
        f.counter += 1
        print("{0}: {1} times".format(f.__name__, f.counter))
        return v
    return counting_f

Solution

  • Not sure to understand what you want. Is it this :

    def counter(*f):
      print len(f)
    
    >>> counter("one", "two")
    2
    
    >>> counter("one", "two","three")
    3