Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
code in a string?
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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'
>>> 
Skaperen likes this post
Reply
#3
Yay! works great!
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020