user3675188
user3675188

Reputation: 7409

How could I dynamically call the function with parameters

Let's say I put the function calls into list,

['next_release()', 'last_release("com_disagg")']

Hope to get the equivalent results of following

How could I get it in Python

iterate the array and dynamically call the function with params.

next_release()
last_release("com_disagg")

call head() method for each function

next_release().head()
last_release("com_disagg").head()

add print for each function

print next_release().head()
print last_release("com_disagg").head()

Upvotes: 0

Views: 64

Answers (3)

Reut Sharabani
Reut Sharabani

Reputation: 31339

Currently you're storing a string representing a function. That's probably not what you want since it'll force you to use eval which is usually bad.

You could get away with a mapping if you have to do it with strings:

mapping = {
    'next_release()': next_release(),
    'last_release("com_disagg")': last_release("com_disagg")
}

And now you can get the result using the mapping (mapping["next_release()"] ...).

There are two better options using actual functions and not strings:

If you want the list to store the functions' results (after calling them):

functions_results = [next_release(), last_release("com_disagg")]
list_of_functions_heads = [x.head() for x in list_of_functions_results]

If you want the list to store a functions' references (notice I closed the function with arguments in a lambda to create a parameter-less function:

functions_references = [next_release, lambda: last_release("com_disagg")]
list_of_functions_heads = [x().head() for x in list_of_functions_results]

Upvotes: 1

Alekhya Vemavarapu
Alekhya Vemavarapu

Reputation: 1155

You can use clsoure:

arr = ['next_release()', 'last_release("com_disagg")']  
def next_release():  
    def head():  
      return x;  

def last_release(var):  
    def head():  
     return y;  

for i in arr:
    print i.head()

Upvotes: 0

Kavin Eswaramoorthy
Kavin Eswaramoorthy

Reputation: 1625

arr = ['next_release()', 'last_release("com_disagg")']
class t(object):
    def head(self):
        print "inside head"
        return "head printed"

def next_release():
    print "nr"
    return t()
def last_release(var):
    print var
    return t()

for i in arr:
    eval(i)

for i in arr:
    print eval(i+".head()")

for i in arr:
    print eval(i).head()

Output:

nr
com_disagg
nr
inside head
head printed
com_disagg
inside head
head printed
nr
inside head
head printed
com_disagg
inside head
head printed

Upvotes: 1

Related Questions