0

I'm trying to copy-paste and run python code which basically looks like this:

mycode = """
    def f():
        print("f called")

    f()
"""

eval(mycode)

And getting error

  File "<string>", line 2
    def f():
    ^
IndentationError: unexpected indent

If I change indent like

mycode = """
def f():
    print("f called")

f()
"""

Then I'm getting error

  File "<string>", line 2
    def f():
      ^
SyntaxError: invalid syntax

Is it a broken code I'm trying to run, or I can fix this somehow? Original code is supposed to be runnable "as is", without any modifications.

I tried this in IPython 3.6.0

TOP KEK
  • 2,593
  • 5
  • 36
  • 62

1 Answers1

2

You cannot define a function in an eval, which is for expressions.

Use exec:

>>> mycode = """
... def f():
...   print("f called")
...
... f()
... """
>>> exec(mycode)
f called
jjmontes
  • 24,679
  • 4
  • 39
  • 51
  • Yep, for me as well. Still not getting why calling f() does not turn statement into expression – TOP KEK Apr 25 '17 at 13:21
  • @TOPKEK Why would it turn it into an expression? The function definition is already not an expression. Adding more things to that is not going to somehow turn it into an expression. – pvg Apr 25 '17 at 13:25
  • Function definition can be a part of expression, no? – TOP KEK Apr 25 '17 at 15:15
  • 1
    No. Expressions must be rvalues, in other words, anything you could use on the right side of an assignment operator (`value = expression`). You can use _lambda_ expressions. – jjmontes Apr 25 '17 at 15:44