3
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 built-in methods for eval() function? For example, allowing only max and min functions.

4 Answers 4

6

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

1
  • 1
    __builtins__ is usually a module. There is no reason that it "should" be a dictionary. It's the second argument passed to eval which should be a dictionary.
    – wim
    Aug 2, 2018 at 18:31
1

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' object is not 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.

0
0

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=5
print(eval("x+1",{'__builtins__': {'min': min, 'max': max, 'x': x}}))
0

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

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.