ast
uses compile
to compile the source string (which must be an expression) into an AST.
If the source string is not a valid expression (like an empty string), a SyntaxError
will be raised by compile
. If, on the other hand, the source string would be a valid expression (e.g. a variable name like foo
), compile
will succeed but then literal_eval
might fail with a ValueError
.
Therefore, you should catch both SyntaxError
and ValueError
when using literal_eval
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…