Skip to content Skip to sidebar Skip to footer

Python Eval Error

x=5 print(eval('x+1',{'__builtins__': None})) Getting Error: TypeError: 'NoneType' object is not subscriptable Why am I getting above error? Also, How to specify only a few

Solution 1:

From the builtins docs:

The value of __builtins__ is normally either this module [builtins] or the value of this module's __dict__ attribute

To fix your error:

>>>print(eval('x+1',{'__builtins__': {'x': x}}))

To specify a few built-in methods, provide it to __builtins__

>>>print(eval('min(1,2)',{'__builtins__': {'min': min}}))

However, limiting __builtins__ is still not safe: see https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

Solution 2:

Why am I getting above error?

Python tries to look for the name 'x' within the builtins you've provided, and fails like that:

>>> None['x']
TypeError: 'NoneType'objectisnot subscriptable

You would need to include x in scope too:

>>>x = 5>>>eval('x+1', {'__builtins__': None, 'x': x})
6

How to specify only a few built-in methods for eval() function?

You can not sandbox this way. It's always possible to escape the sandbox, for example via an attribute access on literals.

Solution 3:

Is the same reason why you don't get defined 'x' if you do:

x=5
print(eval("x+1",{'__builtins__': __builtins__}))

you get: NameError: name 'x' is not defined because you override all your context.

but if you just do:

x=5
print(eval("x+1"))

will print '6' but will use ALL the builtins functions, probably you just wanna do:

x=5print(eval("x+1",{'__builtins__': {'min': min, 'max': max, 'x': x}}))

Solution 4:

One of the possible solutions would be to get current globals end clear the builtins

x=5
dictionary = globals()
dictionary['__builtins__'] = Noneprint(eval('x+1',dictionary))

Post a Comment for "Python Eval Error"