Some_dude
Some_dude

Reputation: 139

How do you write a function with multiple lines in a string format?

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()

Upvotes: 2

Views: 3120

Answers (2)

sal
sal

Reputation: 3593

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()

Upvotes: 1

Andrew Yochum
Andrew Yochum

Reputation: 1056

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.

Upvotes: 1

Related Questions