0

I've been busting my head for a while now with this.

Given this function:

def foo(param1, param2, param3):
    print 'param1 =', param1
    print 'param2 =', param2
    print 'param3 =', param3

is it possible to do something like this in Python?

string1 = 'param1'
string2 = 'param2'
string3 = 'param3'

foo(string1='val1', string2='val2', string3='val3') # Uber magic

or something like this?

params = {
    'param1': 'val1',
    'param2': 'val2',
    'param3': 'val3'
}

foo(params) # Even ubener magic

The result of all the magic should be the equivalent to calling

foo(param1='val1', param2='val2', param3='val3')

I'm not interested in changing the function to support **kwargs by the way.

Thanks in advance!

  • 1
    It's very unclear to me what you want that second one to do. Can you explain in words and give a clear expected output, because tl;dr yes all of those things are possible (without magic :) ) – en_Knight Apr 06 '16 at 21:10
  • The idea is to automagically make the string1 value 'param1' be recognized by the interpreter as the function's param1 parameter, no matter the order in which I pass the string1, string2 or string3 'parameters'. – Ciprian Mandache Apr 06 '16 at 21:14
  • "I'm not interested in changing the function to support `**kwargs` by the way" - whether the function is defined with a `**kwargs` parameter has no connection to whether you can pass it keyword arguments with `**kwargs`. – user2357112 Apr 06 '16 at 21:18
  • 1
    Okay, given that, I'm voiting to close as a dup. I'm sort of surprised there are so many answers here without a flag, this question, if I understand, seems to have many answers on SO [Python normal arguments vs. keyword arguments](http://stackoverflow.com/questions/1419046/python-normal-arguments-vs-keyword-arguments) – en_Knight Apr 06 '16 at 21:38

3 Answers3

2
>>> def foo(param1, param2, param3):
    print param1, param2, param3

>>> foo(*range(3))
0 1 2
>>> foo(**dict(param1=1,param2=2,param3=3))
1 2 3
dbra
  • 621
  • 3
  • 11
1
params = {
    'param1': 'val1',
    'param2': 'val2',
    'param3': 'val3'
}

foo(**params) # Even ubener magic

this is known as unpacking a dictionary ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

As pointed out by @en_Knight these are possible to do

Either:

foo(param1='val1',param2='val2',param3='val3')

or:

foo(**params)

If you want to only specify some of the variables you could give the function default variables(would not be so useful in this exact example):

def foo(param1='', param2='', param3=''):

then you could specify them in any order or omit some of them eg.

foo(param3=2,param1=2)

But if some of the variables are defined without referring to the argument name they need to be put first:

foo(3,param=4) #param1 = 3, param2 = '', param3 = 4
Community
  • 1
  • 1
M.T
  • 4,917
  • 4
  • 33
  • 52