Issue
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
Solution
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
Answered By - jjmontes
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.