ValueError: malformed string when using ast.literal_eval

前端 未结 5 1750
眼角桃花
眼角桃花 2020-11-28 14:08

It is widely known that using eval() is a potential security risk so the use of ast.literal_eval(node_or_string) is promoted

However In python 2.7 it re

5条回答
  •  天命终不由人
    2020-11-28 14:59

    Use the source, luke!

    http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40 http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39

    You will find your answer in there. Specifically, the 2.7 version has the weird restriction on line 70 that the right node of the BinOp is complex.

    >>> sys.version
    '2.7.3 (default, Sep 26 2013, 20:03:06) \n[GCC 4.6.3]'
    >>> ast.literal_eval('9 + 0j')
    (9 + 0j)
    >>> ast.literal_eval('0j + 9')
    ValueError: malformed string
    

    I'm guessing that the intention of 2.7 was to allow literal_eval of complex literals for example numbers like 9 + 0j, and it was never intended to do simple integer additions. Then in python 3 they beefed up the literal_eval to handle these cases.

提交回复
热议问题