Reputation: 335
After looking for some reference online I still do not understand how eval() really works, maybe I am missing a key component, hopefully someone can guide me to the right docs or explanation.
Suppose:
def foo(x,y):
print(x)
print(y)
Use eval() to call foo().
Example 1:
eval('foo(1,2)')
Example 2:
eval('foo')(1,2)
According to python 3.6 documentation, the way I am calling eval() on example is how it should be done, as I am passing everything as a string, However, for example #2 I still do not understand why python interpreter also evaluates correctly.To me when running eval() on the second example the python interpreter should return a TypeError requiring 2 missing arguments. I am hoping if someone can point me in the right direction.
Upvotes: 0
Views: 117
Reputation: 375484
This is a valid Python expression: foo
. It evaluates to the function. You can then call it. This is why foo(1, 2)
works. You can also do this:
x = foo
x(1, 2)
So eval("foo")
evaluates to the function foo, which you can then call.
Upvotes: 4