1

I'm trying to write a function that will contain some default values, with the possibility of having some additional parameters sent in. For example, I would like something along the lines of this:

def defaultsAndArbitrary(arr, example1=True, example2=13, *modifiers):
    #code

Then, I'd like to be able to call the function like so:

defaultsAndArbitrary([1,5,3,9], modifier1, modifier2)

With that call, the values for the arguments should be:

arr = [1,5,3,9]
example1 = True
example2 = 13
modifiers = (modifier1, modifier2)

There's a similar question here:

Having arbitrary number of arguments with a named default in python

But it doesn't really answer this question (at least, to my understanding). Is it even possible to do this?

Thanks.

Community
  • 1
  • 1
user2869231
  • 1,431
  • 5
  • 24
  • 53

2 Answers2

1

In Python 3 you can use keyword-only arguments. That would look something like this:

def defaultsAndArbitrary(arr, *modifiers, example1=True, example2=13):

In Python 2 you must a use a solution like that given in the question you linked to: you must use **kwargs and manually extract example1 and example2 from the kwargs dict, supplying defaults if those kwargs are not passed. This means that you can't specify their names or defaults in the function signature; you have to do it in the code of the function.

Note that in either case, your example1 and example2 variables must be passed by keyword (if you want to pass values for them instead of using the defaults); they cannot be passed positionally.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Ok, well I'm using Python 2.7 so I guess I can't do the first method :/ So in the second case, how do you declare a default without it overwriting the argument sent in? – user2869231 Aug 06 '14 at 21:28
  • @user2869231: The question that you linked to already shows how to do that (as does muraveil's answer). – BrenBarn Aug 06 '14 at 21:35
1

You can do something like this:

def defaultsAndArbitrary(arr, *modifiers, **kwargs):
    example1 = kwargs.get('example1',True)
    example2 = kwargs.get('example2',13)
JulienD
  • 7,102
  • 9
  • 50
  • 84
  • I typed this in, and when I sent in example1 = False, it properly changed it to False. Why is that, though? To me, example1 = kwargs.get('example1', True) is setting the value of example 1 AFTER the arguments are read in, thus overwriting the argument? – user2869231 Aug 06 '14 at 21:31
  • `kwargs.get('example1', True)` is the same as `if 'example1' in kwargs: example1=kwargs['example1']; else: example1=True`. At the time this expression is evaluated, `kwargs` is already set through the function call. – JulienD Aug 06 '14 at 21:36