Skip to content

Instantly share code, notes, and snippets.

@victory-sokolov
Created January 15, 2024 14:05
Show Gist options
  • Save victory-sokolov/2db6ddd5675465a92d8b392460c1f55b to your computer and use it in GitHub Desktop.
Save victory-sokolov/2db6ddd5675465a92d8b392460c1f55b to your computer and use it in GitHub Desktop.
Python String to Code with AST
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