Search code examples
pythonsyntaxinteger

How to consider brackets as multiplication when doing eval in python?


How to consider eval("2(4)") as 8?

When I run this it gives the error of SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?


Editor's note: There is an actual error in addition to the warning. In full (on Python 3.8):

>>> eval("2(4)")
<string>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
TypeError: 'int' object is not callable

Solution

  • In python, eval will run the string you give it, and 2(4) is a call expression.

    call ::=  primary "(" [argument_list [","] | comprehension] ")"
    

    This would make 2 the primary, which needs a __call__ attribute but does not have one as it is just an int.

    Hence the SyntaxWarning: 'int' object is not callable.