user170008
user170008

Reputation: 1066

Literal String substitution in python

Consider the below code snippet in python

argKey = 'actualArgument'

methodA(argKey=argVal) #invoking methodA

where methodA() is defined as :

def methodA(actualArgument, actualArgument2, actualArgument3)

methodA can be invoked only via named arguments ie. you invoke by specifying the argument name and passing the argument value.

--> throws an error :

TypeError: methodA() got an unexpected keyword argument 'argKey '

I want 'methodA' to be invoked by the value contained in the 'argKey' variable i.e

methodA(actualArgument=argVal)

How to get the substitution of the string into the method invocation call.?

Upvotes: 0

Views: 171

Answers (1)

9000
9000

Reputation: 40894

To pass parameters with computed names, use a dict:

def foo(a, b):
  return a+b

name_of_a = 'a'
params = {name_of_a: 1, 'b': 2}
print foo(**params) # note the asterisks

Upvotes: 3

Related Questions