liveBook · Manning

Eval

As explained in Python How-To

eval is Python's built-in function that evaluates a string or code object as a Python expression and returns its result.

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

How Python How-To covers it

How deep it goes
Explains string evaluation, iterable pitfalls, syntax errors, and security risks, but does not develop evaluation internals.
Examples
Demonstrates list, tuple, and dictionary strings, constructor failures, malformed syntax, and manual comma-separated parsing.
What it assumes
Assumes familiarity with Python strings, constructors, iterables, expressions, and basic exception handling.
What you can do after
Apply it via Python's built-in eval to trusted strings representing Python expressions.
How it connects
Connects eval with iterables, constructors, exec, exception handling, parsing, and the ast module.

Also explained in

Compare how 2 books explain eval →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.