Multi-line statements with PLY
I've been experimenting with PLY and was encountering an obscure
error that was surprisingly Google-resistant. I've been building up a language
and a REPL to interpret commands. When trying to parse a statement spanning multiple lines,
I would get an error {TypeError}Can't convert 'type' object to str implicitly
.
Debugging revealed the parser was running into an EOF. The usual sources online didn't
appear to have any information about it, either.
It turns out the problem wasn't PLY, but Python's input()
. It only reads one line at
a time. So even if you paste in
def foo(bar):
print('stuff')
return bar + 10
the method will only pass along the string 'def foo(bar):
. As a workaround,
try something like this:
def evaluate(string):
# your eval function
parser = yacc.yacc()
while True:
string = ''
line = input('reap> ')
while line != '':
string += line
line = input()
print(evaluate(parser.parse(string)))
There's your read-eval-print loop, spanning multiple lines of user input. After your block is finished, hit enter twice to finish the block, and you should be good to go.