Using python's eval() vs. ast.literal_eval()?

前端 未结 6 1254
情深已故
情深已故 2020-11-21 06:39

I have a situation with some code where eval() came up as a possible solution. Now I have never had to use eval() before but, I have come across p

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 07:33

    ast.literal_eval() only considers a small subset of Python's syntax to be valid:

    The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

    Passing __import__('os').system('rm -rf /a-path-you-really-care-about') into ast.literal_eval() will raise an error, but eval() will happily delete your files.

    Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval(). It safely does what you want and nothing more.

提交回复
热议问题