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()
Marki555
6,9803 gold badges43 silver badges60 bronze badges
asked Jul 9, 2015 at 6:46

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
answered Jul 9, 2015 at 6:49
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]
answered Jul 9, 2015 at 6:50

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()
answered Jul 9, 2015 at 6:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.