Which Python function is used to evaluate a string as Python code?

The story behind the answer

The Python function used to evaluate a string as Python code is `eval()`. In its ordinary form, `eval()` parses and evaluates a string containing a single Python expression, then returns that expression’s value.

For example, `eval("2 + 3")` returns `5`, while `eval("name")` looks up the variable `name` in the available evaluation context. Optional `globals` and `locals` mappings let a program control which names are visible during evaluation.

The key distinction is between `eval()` and `exec()`. `eval()` is designed for expressions that produce a value; `exec()` executes statements or larger blocks of code and does not serve as the normal expression-returning counterpart. `compile()` can turn source text into a code object, but it is a compilation function rather than the usual direct evaluator.

Because evaluated text can access powerful Python operations, passing untrusted input to `eval()` can create a serious code-execution vulnerability. Safer parsing or restricted data formats are usually preferable.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: