PyCQA / redbaron

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

Indent of function docstrings always four spaces #219

Closed JohannesBuchner closed 1 year ago

JohannesBuchner commented 1 year ago

Thank you for creating redbaron. I am writing a tool to pre-generate numpy-style parameter documentation.

Attaching a docstring to a function gives a somewhat arbitrary indent:

import redbaron
rb = redbaron.RedBaron("""
class Foo():
    def bar():
        pass
""")
barfunc = rb.find('def')

barfunc.value.insert(0, '''"""bar function.

Does beautiful things.
"""''')
print(rb.dumps())

Actual result:

class Foo():
    def bar():
        """bar function.

    Does beautiful things.
    """
        pass

Expected result:

class Foo():
    def bar():
        """bar function.

        Does beautiful things.
        """
        pass

The behaviour also occurs in nested functions:

def foo():
    def bar():
        pass

The current behaviour of redbaron seems to assume:

  1. that the indent method is 4 spaces (not tabs)
  2. that the function to document is at file level and not in a deeper level (function in a function, method of a class)

Please let me know if this is the intended behaviour or whether you consider this a bug.

If the user of redbaron is supposed to work around this somehow, please let me know how, because it seems quite difficult to guess and fix the indent.

JohannesBuchner commented 1 year ago

I was able to solve this with the indentation attribute like this:

    barfunc.value.insert(0, textwrap.indent('''"""%s function.

Does beautiful things.
"""''' % barfunc.name, barfunc.value[0].indentation).lstrip())
JohannesBuchner commented 1 year ago

The gendocstr.py tool is available here as part of pystrict3 if you are interested: https://github.com/JohannesBuchner/pystrict3#gendocstrpy-tool