.. function:: literal_eval(node_or_string)
- Safely evaluate an expression node or a string containing a Python literal or
+ Evaluate an expression node or a string containing only a Python literal or
container display. The string or node provided may only consist of the
following Python literal structures: strings, bytes, numbers, tuples, lists,
dicts, sets, booleans, and ``None``.
- This can be used for safely evaluating strings containing Python values from
- untrusted sources without the need to parse the values oneself. It is not
- capable of evaluating arbitrarily complex expressions, for example involving
- operators or indexing.
+ This can be used for evaluating strings containing Python values without the
+ need to parse the values oneself. It is not capable of evaluating
+ arbitrarily complex expressions, for example involving operators or
+ indexing.
+
+ This function had been documented as "safe" in the past without defining
+ what that meant. That was misleading. This is specifically designed not to
+ execute Python code, unlike the more general :func:`eval`. There is no
+ namespace, no name lookups, or ability to call out. But it is not free from
+ attack: A relatively small input can lead to memory exhaustion or to C stack
+ exhaustion, crashing the process. There is also the possibility for
+ excessive CPU consumption denial of service on some inputs. Calling it on
+ untrusted data is thus not recommended.
.. warning::
- It is possible to crash the Python interpreter with a
- sufficiently large/complex string due to stack depth limitations
- in Python's AST compiler.
+ It is possible to crash the Python interpreter due to stack depth
+ limitations in Python's AST compiler.
.. versionchanged:: 3.2
Now allows bytes and set literals.
def literal_eval(node_or_string):
"""
- Safely evaluate an expression node or a string containing a Python
+ Evaluate an expression node or a string containing only a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
sets, booleans, and None.
+
+ Caution: A complex expression can overflow the C stack and cause a crash.
"""
if isinstance(node_or_string, str):
node_or_string = parse(node_or_string, mode='eval')