Parse Data Instead of Executing Dynamic Code
Core idea
eval and exec interpret Python code, not a data format. Never send untrusted input to them. Use an explicit parser such as json.loads for structured data or int for an integer, followed by validation. ast.literal_eval is not a general safe untrusted-input parser: complex literals can exhaust resources. If a choice maps to behavior, use a fixed allowlist of functions.
import jsonraw = '{"count": 4}'if len(raw) > 100: raise ValueError('too long')record = json.loads(raw)if not isinstance(record, dict) or set(record) != {'count'} or type(record['count']) is not int: raise ValueError('invalid record')print(record['count'])The input is treated as JSON and checked against the expected schema.
Expected output:
4Choose only defined operations
def double(n): return n * 2operations = {'double': double, 'identity': lambda n: n}def apply(name, value): if name not in operations: return 'unsupported' return operations[name](value)print(apply('double', 4))print(apply('unknown', 4))A fixed mapping selects trusted functions, without interpreting the submitted name as code.
Expected output:
8unsupportedCommon mistake
Do not try to make eval safe by deleting a few built-in names or filtering keywords. Select a data format and define a small accepted input contract instead.
Practice
Replace an expression-like configuration with a JSON object containing an operation name and bounded integer. Test unknown operations and malformed JSON without executing supplied code.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unsafe dynamic execution
Check your understanding of unsafe dynamic execution.
What is printed?
import jsonprint(json.loads("[1,2]")[1])What is printed?
choices={"a":3}print(choices.get("b","unsupported"))What should interpret an external JSON record?
Why limit input even for literal_eval?