PyCQA / redbaron

Bottom-up approach to refactoring in python
http://redbaron.pycqa.org/
694 stars 74 forks source link

"dumps" creates wrong indentation inside a for loop #184

Open vsjha18 opened 5 years ago

vsjha18 commented 5 years ago

If you iterate on a function node and issue "dumps" on each line, then any if/else block is incorrectly indented.

Use this code to reproduce the problem

In [1]: import redbaron

In [2]: code = """
   ...: def foo():
   ...:     simple_code()
   ...:     # a comment
   ...:     if x is True:
   ...:         add()
   ...:     else:
   ...:         sub()
   ...: """

In [3]: tree = redbaron.RedBaron(code)

In [4]: defnode = tree[1]

In [5]: type(defnode)
Out[5]: redbaron.nodes.DefNode

In [6]: for line in defnode:
   ...:     print(line.dumps())
   ...:
simple_code()
# a comment
if x is True:
        add()
    else:
        sub()

As you can see above if and else are not in the same vertical alignment.

As per my use case I am extracting all the metadata from the attributes of the defnode and I need to unparse the function body line by line. I am able to do it easily with ast by I am loosing all the code comments, which I want to preserve. If somehow this indentation issue is resolved, then I am all done !