-1

In python, I have code like this:

def var(a=1, b=2, c=3):
        return a, b, c

Running it gives this outcome:

>>> import Test
>>> Test.var()
(1, 2, 3)

In this case, 1, 2 and 3 are the default values I want to use. Occasionally, I want to be able to modify all or some of those variables. However, because I have many possible var() statements with different defaults and number of defaults. They can be var(a=1, b=2, c=3) or var(d=1, e=2, f=3, g=4) or var(h=0) and so on.

I want to modify these variables through a single variable I can feed from command line, like this:

>>> arguments = 'a=0, b=5, c=7'

But this doesn't work.

>>> Test.var(arguments)
('a=0, b=5, c=7', 2, 3)

It interprets the 'arguments' variable as being only 'a' while leaving b and c untouched. How can I make my 'arguments' variable be read literally by the def statement?

2 Answers2

2

You can unpack a tuple or a dictionary into arguments. This means all of the following are equal:

keyword_arguments = {'a':0, 'b':5, 'c':7}
positional_arguments = (0, 5, 7)

Test.var(0, 5, 7)
Test.var(a=0, b=5, c=7)
Test.var(*positional_arguments)
Test.var(**keyword_arguments)
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
0

You can either use a list or a dictionary that you use as argument for the function:

   >>> arglist = [5,6,7]
   >>> var(*arglist)
   (5, 6, 7)
   >>> argdict = {'b':4,'a':3, 'c':5}
   >>> var(**argdict)
   (3, 4, 5)
redimp
  • 1,061
  • 8
  • 12