Search code examples
pythonpython-3.xeval

print function not printing appropriate output using eval


I am getting 2 different outputs using 2 similar commands:

>>> inp = 'print("hi")'
>>> print(eval(inp))
hi
None
>>> eval(inp)
hi

How to I make print(eval(inp)) print just 'hi'? Why is None printing as well?


Solution

  • So here's what happens when you do print(eval('print("hi")')):

    1. eval() is called, with the argument 'print("hi")'
    2. Accordingly, the code print("hi") is executed
    3. "hi" is printed to the console
    4. Having finished executing, print() returns None.
    5. Having executed the code 'print("hi")', the eval() function records the return call of that function. Which was None.
    6. Accordingly, eval() returns None, since that was the result of the code it ran.
    7. The outer print() call is supposed to print whatever the eval() function returned. Now it looks like print(None).
    8. None is printed to console.

    tl;dr, print() is called two different times. Thus, two different things are printed: "hi" the first time, and None the second time.


    If all you want is to print "hi", you can just do eval('print("hi")') - or you could do print(eval("hi")), since in this case eval() would return "hi" and that's what would be printed. In either of those cases you would only ever be executing one print statement.

    Though, in general, please do not use eval() for anything. It's notoriously risky, prone to errors that can completely break your program, and there's nothing you can do with it that you can't do with the code you'd put inside it. The only feasible reason for using eval() would be to respond dynamically to user-generated code, which is a terrible idea because it allows code injections. The user shouldn't be able to do that.