Python Forum

Full Version: code in a string?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
has a way been worked out to have a block of source code be assigned to a string while also compiling the code as if that code was there without being assigned to a string?
I just found a way
>>> exec(s := "print('hello')")
hello
>>> s
"print('hello')"
Same with several statements
>>> exec(s := """\
... def foo(x):
...     print(x, x)
... 
... y = 100
... """)
>>> y
100
>>> foo(y)
100 100
>>> s
'def foo(x):\n    print(x, x)\n\ny = 100\n'
>>> 
Yay! works great!