2

I am searching how I could use optional arguments in python. I have read this question but it is not clear to me. Lets say I have a function f that can take 1 or more arguments to understand time series. Am i obliged to specify the number of arguments and set default values for each argument? What I aim to do is being able to write a function this way:

simple function:

def f(x,y):
    return x + y
#f(1,2) returns 3

What i want is also f(1,2,3) to return me 6 and f(7) returning me 7

Is it possible to write it without setting a predefined number of mandatory/optional parameters? Is it possible to write it without having to set default values to 0 ? How to write this function?

Its a simple example with numbers but the function i need to write is comparing a set of successive objects. After comparison is done, the data set will feed a neural network.

Thanks for reading.

EDIT: Objects I am feeding my function with are tuples like this (float,float,float,bool,string)

Community
  • 1
  • 1

3 Answers3

4
def f(*args):
    """
        >>> f(1, 2)
        3

        >>> f(7)
        7

        >>> f(1, 2, 3)
        6

        >>> f(1, 2, 3, 4, 5, 6)
        21
    """
    return sum(args)

If you need to do something more complicated than sum you could just iterate over args like this:

def f(*args):
    r = 0
    for arg in args:
        r += arg
    return r

See this question for more information on *args and **kwargs

Also see this sections on the Python tutorial: Arbitray Argument List

Community
  • 1
  • 1
Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
  • You should show OP how to do the summation in a loop to make it slightly more explicit that `args` is a tuple in the function. (But don't delete the answer with `sum`. Ultimately, that's more idiomatic) – mgilson Oct 25 '12 at 15:40
4

You can put *args in your function and then take arbitrary (non-keyword) arguments. *args is a tuple, so you can iterate over it like any Python tuple/list/iterable. IE:

def f(*args):
    theSum = 0
    for arg in args:
        theSum += arg
    return theSum

print f(1,2,3,4)
Doug T.
  • 64,223
  • 27
  • 138
  • 202
1

You can use the follow syntax:

def f(*args):
    return sum(args)

The * before args tells it to "swallow up" all arguments, makng args a tuple. You can also mix this form with standard arguments, as long as the *args goes last. For example:

def g(a,b,*args):
    return a * b * sum(args)

The first example uses the built-in sum function to total up the arguments. sum takes a sequence as adds it up for you:

>>> sum([1,3,5])
9
>>> sum(range(100))
4950

The args name is not mandatory but is used by convention so best to stick with it. There is also **kwargs for undefined keyword arguments.

David Webb
  • 190,537
  • 57
  • 313
  • 299