Tutorial by Examples

>>> code = """for i in range(5):\n print('Hello world!')""" >>> exec(code) Hello world! Hello world! Hello world! Hello world! Hello world!
>>> expression = '5 + 3 * a' >>> a = 5 >>> result = eval(expression) >>> result 20
compile built-in function can be used to precompile an expression to a code object; this code object can then be passed to eval. This will speed up the repeated executions of the evaluated code. The 3rd parameter to compile needs to be the string 'eval'. >>> code = compile('a * b + c', '&l...
>>> variables = {'a': 6, 'b': 7} >>> eval('a * b', globals=variables) 42 As a plus, with this the code cannot accidentally refer to the names defined outside: >>> eval('variables') {'a': 6, 'b': 7} >>> eval('variables', globals=variables) Traceback (most ...
If you have a string that contains Python literals, such as strings, floats etc, you can use ast.literal_eval to evaluate its value instead of eval. This has the added feature of allowing only certain syntax. >>> import ast >>> code = """(1, 2, {'foo': 'bar'})&quot...
It is not possible to use eval or exec to execute code from untrusted user securely. Even ast.literal_eval is prone to crashes in the parser. It is sometimes possible to guard against malicious code execution, but it doesn't exclude the possibility of outright crashes in the parser or the tokenizer....

Page 1 of 1