1

I've been recently trying with some program synthesis. Here, I'm generating strings, that represent valid functions. My current solution includes printing the string to stdout, storing them to a file, and calling that file from somewhere else. However, can the functions be directly imported into a given namespace? Assume the following example:

def sum2(x):
    return sum(x)

print(sum2([1,2,3]))


sstring = """
def sum3(x):
    return sum(x)
"""

eval(sstring)
print(sum3([1,2,3]))

Is anything like the second part (which does not work) possible? Is eval() limited to primitive expressions?

martineau
  • 119,623
  • 25
  • 170
  • 301
sdgaw erzswer
  • 2,182
  • 2
  • 26
  • 45
  • `eval` only works with expressions (things that evaluate to a value, i.e., something you can assign to a variable, `x = `), `exec` takes arbitrary statements – juanpa.arrivillaga Jul 29 '20 at 09:48

2 Answers2

1

eval's bigger brother exec will help you here.

def sum2(x):
    return sum(x)

print(sum2([1,2,3]))


sstring = """
def sum3(x):
    return sum(x)
"""

exec(sstring)
print(sum3([1,2,3]))
JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24
1

It works if you compile it:

eval(compile(sstring, '', 'single'))

Demo at repl.it.

superb rain
  • 5,300
  • 2
  • 11
  • 25