NathanaëlBeau
NathanaëlBeau

Reputation: 1152

'\n' creates an indentation while parsing python code with ast.parse

I'm trying to parse with ast.parse in Python 3.7 (https://docs.python.org/3/library/ast.html) the following snippet of code :

from functools import reduce 
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])

I use the code below :

py_ast = """from functools import reduce \n reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"""

py_ast = ast.parse(py_ast)

And i got this error :

File "", line 2 --> reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5]) IndentationError: unexpected indent

I understand the use of \n is creating an indent, how can I avoid it?

Upvotes: 0

Views: 397

Answers (1)

Rolv Apneseth
Rolv Apneseth

Reputation: 2118

You're using triple quotes so why not leave out the \n altogether and just hit enter, the string will stay formatted how you want it.

This code runs fine for me:

import ast

py_ast = """from functools import reduce
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"""

py_ast = ast.parse(py_ast)

print(py_ast)
>>> <ast.Module object at 0x0000019F2E140FD0>

Upvotes: 2

Related Questions