0

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.

1
  • foo is a valid Python expressions. Functions are just another type of object. Try it in the interpreter Commented Jul 4, 2018 at 22:25

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.