Issue
I am trying to run this code but it seems that the exec()
is not executing the string inside the function:
def abc(xyz):
for i in fn_lst:
s = 'temp=' + i + '(xyz)'
exec(s)
print (temp)
abc('avdfbafadnf')
The error I am receiving:
NameError Traceback (most recent call last)
<ipython-input-23-099995c31c78> in <module>()
----> 1 abc('avdfbafadnf')
<ipython-input-21-80dc547cb34f> in abc(xyz)
4 s = 'temp=' + i + '(word)'
5 exec(s)
----> 6 print (temp)
NameError: name 'temp' is not defined
fn_lst
is a list of function names i.e: ['has_at', 'has_num' ...]
Please let me know an alternative to exec()
if possible in such a scenario.
Solution
Instead of using exec
with function names, just keep the function objects in the list:
fn_lst = [has_at, has_num, ...]
and perform the call directly:
def abc(xyz):
for i in fn_lst:
temp= i(xyz)
print(temp)
Answered By - Dimitris Fasarakis Hilliard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.