Search code examples
pythoneval

Error with eval() function with print function in python


I am trying to run this in Python IDLE:

>>> eval(print("123*13"))

I get the output correctly, but it comes with a TypeError:

123*13
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    eval(print("123*13"))
TypeError: eval() arg 1 must be a string, bytes or code object

NOTE:
I do NOT want to do print(eval("123*13")).
I want to use print() in eval() function. This is NOT for actual implementation, but I got this error while using eval() function. I am not asking this for any actual implementation, but curiosity.


Solution

  • Use it:

    eval('print("123*13")')
    

    in eval() src:

    evel (__source: str | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ...) -> Any
    '''Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression    
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.'''
    ...
    
    

    eval help():

    eval(source, globals=None, locals=None, /)
        Evaluate the given source in the context of globals and locals.
    
        The source may be a string representing a Python expression
        or a code object as returned by compile().
        The globals must be a dictionary and locals can be any mapping,
        defaulting to the current globals and locals.
        If only globals is given, locals defaults to it.
    

    You can see more in Python.org.