What does Python's eval() do?

前端 未结 10 2096
后悔当初
后悔当初 2020-11-22 01:48

In the book that I am reading on Python, it keeps using the code eval(input(\'blah\'))

I read the documentation, and I understand it, but I still do no

相关标签:
10条回答
  • 2020-11-22 02:35

    Maybe a misleading example of reading a line and interpreting it.

    Try eval(input()) and type "1+1" - this should print 2. Eval evaluates expressions.

    0 讨论(0)
  • 2020-11-22 02:41

    One of useful applications of eval() is to evaluate python expressions from string. For example load from file string representation of dictionary:

    running_params = {"Greeting":"Hello "}
    fout = open("params.dat",'w')
    fout.write(repr(running_params))
    fout.close()
    

    Read it out as a variable and edit it:

    fin = open("params.dat",'r')
    diction=eval(fin.read())
    diction["Greeting"]+="world"
    fin.close()
    print diction
    

    Output:

    {'Greeting': 'Hello world'}
    
    0 讨论(0)
  • 2020-11-22 02:41

    Another option if you want to limit the evaluation string to simple literals is to use ast.literal_eval(). Some examples:

    import ast
    
    # print(ast.literal_eval(''))          # SyntaxError: unexpected EOF while parsing
    # print(ast.literal_eval('a'))         # ValueError: malformed node or string
    # print(ast.literal_eval('import os')) # SyntaxError: invalid syntax
    # print(ast.literal_eval('1+1'))       # 2: but only works due to a quirk in parser
    # print(ast.literal_eval('1*1'))       # ValueError: malformed node or string
    print(ast.literal_eval("{'a':1}"))     # {'a':1}
    

    From the docs:

    Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

    This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

    As for why it's so limited, from the mailing list:

    Allowing operator expressions with literals is possible, but much more complex than the current implementation. A simple implementation is not safe: you can induce basically unbounded CPU and memory usage with no effort (try "9**9**9" or "[None] * 9**9").

    As for the usefulness, this function is useful to "read back" literal values and containers as stringified by repr(). This can for example be used for serialization in a format that is similar to but more powerful than JSON.

    0 讨论(0)
  • 2020-11-22 02:42

    eval(), as the name suggests, evaluates the passed argument.

    raw_input() is now input() in python 3.x versions. So the most commonly found example for the use of eval() is its use to provide the functionality that input() provided in 2.x version of python. raw_input returned the user-entered data as a string, while input evaluated the value of data entered and returned it.

    eval(input("bla bla")) thus replicates the functionality of input() in 2.x, i.e., of evaluating the user-entered data.

    In short: eval() evaluates the arguments passed to it and hence eval('1 + 1') returned 2.

    0 讨论(0)
提交回复
热议问题