def literal_eval(node_or_string):
_safe_names = {<EOL>'<STR_LIT:None>': None,<EOL>'<STR_LIT:True>': True,<EOL>'<STR_LIT:False>': False,<EOL>'<STR_LIT>': dict,<EOL>'<STR_LIT:list>': list,<EOL>'<STR_LIT>': sorted<EOL>}<EOL>if isinstance(node_or_string, str):<EOL><INDENT>node_or_string = parse(node_or_string, mode='<STR_LIT>')<EOL><DEDENT>if isinstance(node_or_string, ast.Expression):<EOL><INDENT>node_or_string = node_or_string.body<EOL><DEDENT>def _convert(node):<EOL><INDENT>if isinstance(node, ast.Str):<EOL><INDENT>return node.s<EOL><DEDENT>elif isinstance(node, ast.Num):<EOL><INDENT>return node.n<EOL><DEDENT>elif isinstance(node, ast.Tuple):<EOL><INDENT>return tuple(map(_convert, node.elts))<EOL><DEDENT>elif isinstance(node, ast.List):<EOL><INDENT>return list(map(_convert, node.elts))<EOL><DEDENT>elif isinstance(node, ast.Dict):<EOL><INDENT>return dict((_convert(k), _convert(v)) for k, v<EOL>in zip(node.keys, node.values))<EOL><DEDENT>elif isinstance(node, ast.Name):<EOL><INDENT>if node.id in _safe_names:<EOL><INDENT>return _safe_names[node.id]<EOL><DEDENT><DEDENT>elif isinstance(node, ast.BinOp):<EOL><INDENT>left = _convert(node.left)<EOL>right = _convert(node.right)<EOL>op = {<EOL>ast.Add: operator.add,<EOL>ast.Sub: operator.sub,<EOL>ast.Mult: operator.mul,<EOL>ast.Div: operator.div,<EOL>ast.Mod: operator.mod<EOL>}.get(type(node.op), None)<EOL>if op:<EOL><INDENT>return op(left, right)<EOL><DEDENT><DEDENT>elif isinstance(node, ast.Call):<EOL><INDENT>func = _convert(node.func)<EOL>args = list(map(_convert, node.args))<EOL>kwargs = dict((kw.arg, _convert(kw.value)) for kw in node.keywords)<EOL>if node.starargs:<EOL><INDENT>args.extend(_convert(node.starargs))<EOL><DEDENT>if node.kwargs:<EOL><INDENT>kwargs.update(_convert(node.kwargs))<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>elif isinstance(node, ast.Attribute):<EOL><INDENT>if not node.attr.startswith('<STR_LIT:_>'):<EOL><INDENT>return getattr(_convert(node.value), node.attr)<EOL><DEDENT><DEDENT>raise ValueError('<STR_LIT>' % node)<EOL><DEDENT>return _convert(node_or_string)<EOL>
Safely evaluate an expression node or a string containing a Python
expression.  The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.