2

I want to write a function, so it can be read as a string when using compile(), but the function has more than one line, so I don't know how to write it.

this is what I want to try to write

def function():
    string = "string"
    print(string)

new_func = "def function(): string = 'strung' # I don't know how to include the other line here "

new_code = compile(new_func,"",'exec')

eval(new_code)

function()

I would like a way to write the function in just one line (or any other way to format this still using eval() and compile()

Some_dude
  • 139
  • 1
  • 8

2 Answers2

1

Looks like you'd like to use a multi-line string. Try the triple quotes at the beginning and end of the string:

def function():
    string = "string"
    print(string)

new_func = """
def do_stuff():
    string = 'strung' #one line
    print(string) #two lines

"""


new_code = compile(new_func,"",'exec')

eval(new_code)

function()
do_stuff()

See this answer for other styles of multi-line strings available: Pythonic way to create a long multi-line string

Have fun.

Andrew Yochum
  • 1,056
  • 8
  • 13
1

You could use python multi-line, as suggested by Andrew. If instead you want a single line, then just remember to use \n and \t in your function string, so that you don't mess out the indentation. For example:

# normal function definition
#
def function():
    string = "string"
    print(string)


# multi-line    
#
new_func = """
def do_stuff(): 
    string = 'strung' # I don't know how to include the other line here
    print(string)"""

# single line, note the presence of \n AND \t
#
new_func2 = "def do_stuff2():\n\tstring = 'strong'\n\tprint(string)\n"

new_code = compile(new_func, "", 'exec')
new_code2 = compile(new_func2, "", 'exec')

eval(new_code)
eval(new_code2)

function()
do_stuff()
do_stuff2()
sal
  • 3,515
  • 1
  • 10
  • 21