Reputation: 636
My intention is to do this:
config = {"methods": ["function1(params1)", "function2(params2)"] }
This I read from a json file. So to use it, I need to pass it to another function as follows:
for method in config[methods]:
foo(global()[method])
I know this wont work as the globals only converts the function name from a string to function but i need this to work for functions with parameters as well.
Also I have thought of this:
config = {"methods": [("function1", params1) , ("function2", params2)] }
for method in config[methods]:
foo(global()[method[0]](method[1]))
This will work but I might have some functions for which I wouldn't require parameters. I don't want to have a condition check for whether the second entry in the tuple exists.
Is there any other way around this? I am open to change in the entire approach including the input format. Please do suggest.
Upvotes: 1
Views: 91
Reputation: 18427
Here's a slight modification of @sshashank124 answer, which is simpler because it accepts the data differently. I think using 'f(arg1, arg2)'
is not so intuitive, and gets very repetitive. Instead, I make it to dictionary pointing to a list of lists, each one represents an execution and only contains the arguments, thusly:
config = { "methods": {"a": [ ["hello"], ["hello","bye"], [] ]} }
means:
a("hello")
a("hello", "bye")
a()
I'm not sure it's any better than Shank's version, but I think it's easier to understand:
def a(*args):
for i in args:
print i
config = { "methods": {"a": [ ["hello"], ['hello','bye'], [] ]} }
for f,args in config['methods'].items():
for arg in args:
globals()[f](*arg)
Upvotes: 0
Reputation: 32189
Here is a simplified example that works with any number of parameters:
from re import findall
def a(*args):
for i in args:
print i
config = {"methods": ["a('hello')", "a('hello','bye')", "a()"]}
for i in config['methods']:
x,y = findall(r'(.*?)\((.*?)\)', i)[0]
y = [i.strip() for i in y.split(',')]
globals()[x](*y)
[OUTPUT]
'hello'
'hello'
'bye'
Upvotes: 2