Need to recover Python data from text? eval treats a string as though it were entered as Python code, evaluates the expression, and returns the resulting value. This is useful when strings represent lists, tuples, or dictionaries rather than ordinary character sequences. section 2.2.3
Convert represented data
numbers_list_str = "[1, 2]" numbers_tuple_str = "(1, 2)" numbers_dict_str = "{1:'one', 2: 'two'}" assert eval(numbers_list_str) == [1, 2] assert eval(numbers_tuple_str) == (1, 2) assert eval(numbers_dict_str) == {1: 'one', 2: 'two'}
Do not replace eval with list or tuple constructors for this task: strings are iterables, so those constructors produce character sequences. Malformed text can raise SyntaxError, and untrusted text can execute dangerous operations. Use eval only with trusted data; otherwise parse the format yourself or consider the ast module. section 2.2.3 section 2.2.4
Keep these distinctions in mind:
- eval evaluates and returns an expression; exec can run expressions and statements but returns nothing. section 2.2.3
- For simple numeric strings, int or float may be appropriate, but failed conversions require try...except handling. section 2.2.4

