Created
January 15, 2024 14:05
-
-
Save victory-sokolov/2db6ddd5675465a92d8b392460c1f55b to your computer and use it in GitHub Desktop.
Python String to Code with AST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import compile | |
# define the source code | |
src = ''' | |
def foo(x): | |
return x + 1 | |
print(foo(1)) | |
''' | |
# parse the source code into an AST | |
tree = ast.parse(src) | |
# generate the bytecode from the AST | |
code = compile(tree, '<string>', 'exec') | |
# execute the bytecode | |
exec(code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment