The difference between using eval () and Ast.literal_eval () in Python

Source: Internet
Author: User

The Eval function is useful for converting data types in Python. Its role is to restore the data to itself or to a data type that can be transformed into.

So what is the difference between Eval and Ast.literal_val ()?

Eval does not know what to convert before doing the calculation is not a valid (secure) Python data type. Just calculate when calling the function. If the computed content is not a valid Python type, an exception is thrown.

Ast.literal will determine whether the content that needs to be computed is not a valid Python type after calculation, and if it does, it will not perform the operation.


------------------------------quoted from StackOverflow--------------------------------

datamap = eval(raw_input(‘Provide some data here: ‘)means that actually evaluate the codebeforeYou deem it to is unsafe or not. It evaluates the code as soon as the function is called. See also the dangers ofeval.

ast.literal_evalRaises an exception if the input isn ' t a valid Python datatype, so the code won ' t is executed if it's not.

Use  ast.literal_eval  whenever you need eval . If you have a Python expressions as an input so want to evaluate, you shouldn ' t (with them).

ShareEdit Edited Mar 4 ' at 8:59
answeredMar 4 ' at 8:52Volatility
13.4k 3 26 -
Add a Comment

The difference between using eval () and Ast.literal_eval () in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.