views:

49

answers:

1

Let's say we have

def Foo(Bar=0,Song=0):  
    print(Bar)
    print(Song)

And I want to assign any one of the two parameters in the function with the variable sing and SongVal:

Sing = Song
SongVal = 2

So that it can be run like: Foo(Sing=SongVal) Where Sing would assign the Song parameter to the SongVal which is 2. The result should be printed like so:

0
2

So should I rewrite my function or is it possible to do it the way I want to? (With the code above you get an error saying Foo has no parameter Sing. Which I understand why, any way to overcome this without rewriting the function too much? Thanks in advance!

+2  A: 

What you're looking for is the **kwargs way of passing arbitrary keyword arguments:

kwargs = {Sing: SongVal}
foo(**kwargs)

See section 4.7 of the tutorial at www.python.org for more examples.

Thomas Wouters
Worked, thanks!Only things that needed changing was Sing should equal a string Sing = "Song"
`Sing` was already `"Song"` in your question.
Thomas Wouters