【问题标题】:Extract method's docstring without meaningless whitespaces提取方法的文档字符串,没有无意义的空格
【发布时间】:2022-09-29 22:55:10
【问题描述】:

在 Python 中,可以提取函数的文档字符串:

class MyClass:
    def my_method(self):
        \"\"\"This is the help message,
        on multiple lines.
        \"\"\"
        pass

print(MyClass.my_method.__doc__)

结果是:

This is the help message,
        on multiple lines.

令人讨厌的是它会导致许多无意义的空格:空格的存在是为了保持代码干净,但并不意味着成为消息的一部分。

有没有办法摆脱它们?请注意,我想删除只有无意义的.因此,调用 lstrip 或等效的将不起作用。

如果有有意义的空间,我想保留它们:

class MyClass2:
    def my_method(self):
        \"\"\"This is the help message,
        on multiple lines.
            This one is intentionally more indented.
        \"\"\"
        pass

print(MyClass2.my_method.__doc__)

期望的结果:

This is the help message,
on multiple lines.
    This one is intentionally more indented.
  • 你不能在新行上拆分,剥离并加入吗?

标签: python


【解决方案1】:

PEP-257: Handling Docstring Indentation 获取代码 sn-p

def trim(docstring):
    if not docstring:
        return ''
    # Convert tabs to spaces (following the normal Python rules)
    # and split into a list of lines:
    lines = docstring.expandtabs().splitlines()
    # Determine minimum indentation (first line doesn't count):
    indent = sys.maxsize
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    # Remove indentation (first line is special):
    trimmed = [lines[0].strip()]
    if indent < sys.maxsize:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())
    # Strip off trailing and leading blank lines:
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    # Return a single string:
    return '\n'.join(trimmed)

输出:

# Class 1
>>> print(trim(MyClass.my_method.__doc__))
This is the help message,
on multiple lines.

# Class 2
>>> print(trim(MyClass2.my_method.__doc__))
This is the help message,
on multiple lines.
    This one is intentionally more indented.

【讨论】:

  • 谢谢!感谢您的回答,我在inspect 模块中找到了解决方案。
【解决方案2】:

感谢 ThePyGuy 的回答,我找到了以前找不到的 related post,这导致了以下解决方案:

inspect.cleandoc(MyClass2.my_method.__doc__)

【讨论】:

    猜你喜欢
    • 2022-11-05
    • 2011-11-15
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多