So recently I learned that eval() is a surprising function that can turn a string into a code command, it could be quite useful when writing a function where an argument is a string of a function's name.
But I wonder what is more pythonic way of using it. Example:
a = [1,2,3,1,2,3,4,1,2,5,6,7]
b = 'count'
target = 2
# regular way
print(a.count(target)) # >>> 3
I tried to write with f-string, which it would work:
print(eval(f'{a}' + '.' + b + f'({target})')) # >>> 3
What amazed me is that it will work even if I don't use f-string:
print(eval('a' + '.' + b + '(target)')) # >>> 3
This is now a little questioning to me, because without f-string, 'a' can be confusing, it won't be easy to tell if this is just a string or a variable pretending to be a string.
Not sure how you guys think about this? Which one is more pythonic to you?
Thanks!