0

Let's say I have something like this:

expr="
def something():
     return True
something()"

somevar=compile(expr, "","eval")

This throws a syntax error on "def". I've also tried wrapping the compile() with an eval(), no use. I basically want the result of the function call. Is this possible with eval or compile? Is there any library that would achieve this? I want somevar to be False. Thanks in advance

1 Answers1

1

According to the docs:

The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement

So there's a couple of things here:

  1. You should use multi-line strings in Python (three """)
  2. You shouldn't use "eval" but "exec"
  3. The returned object is not executed. You have to explicitly call it once created.

With all that in mind:

expr = """
def something():
    print('hi')
    return "done"

something()
"""

somevar = compile(expr, "", "exec")
exec(somevar)

This does print "hi". However, that code itself doesn't return anything. You run the function something() which yes: returns "done" but after running something()? Where would you return the return?

One option, as explained in this other SO thread would be assigning the return value to what would become a sort of "global" variable:

expr = """
def something():
    return "done"

retval = something()
"""

somevar = compile(expr, "", "exec")
exec(somevar)
print(retval)

I can't help but saying that this sort of convoluted coding, that runs code stored in strings is probably a bad idea. It's insecure, hard to track, debug, refactor... So if this is going to be used for something besides learning purposes... Well... I would invite you to try and think if there's another way of achieving what you want.

Savir
  • 17,568
  • 15
  • 82
  • 136