0

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()

3 Answers 3

1
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
Sign up to request clarification or add additional context in comments.

1 Comment

You are not calling head ?
1

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]

Comments

0

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.