【问题标题】:How to write docstrings for functions written in functional paradigm using pipetools如何使用 pipetools 为以功能范式编写的函数编写文档字符串
【发布时间】:2021-09-24 02:13:49
【问题描述】:

我使用pipetools编写函数,这是一个“python的函数管道库”。

一个示例函数(来自他们的docs):

pyfiles_by_length = (pipe
    | os.listdir
    | where(X.endswith('.py'))
    | sort_by(len).descending
    | (enumerate, X, 1)
    | foreach("{0}. {1}")
    | '\n'.join)

这是一个函数定义。我们如何为这样的函数编写文档字符串

我尝试过的:

  1. 函数前注释(PRO:干净简单。CON:不适用于文档库)
# print python filenames in descending order by length
pyfiles_by_length = (pipe
    | os.listdir
    | where(X.endswith('.py'))
    | sort_by(len).descending
    | (enumerate, X, 1)
    | foreach("{0}. {1}")
    | '\n'.join)
  1. __doc__(PRO:使用文档库,CON:不干净和简单)
pyfiles_by_length = (pipe
    | os.listdir
    | where(X.endswith('.py'))
    | sort_by(len).descending
    | (enumerate, X, 1)
    | foreach("{0}. {1}")
    | '\n'.join)
pyfiles_by_length.__doc__ = 'print python filenames in descending order by length'

【问题讨论】:

  • @TylerH “干净和简单”并不是无关紧要的,如果您谈论的是一个团队在大型代码库上交流代码。
  • 是的,是的,因为它是基于意见的,并且这些指标不是在这里要询问的主题指标。一个人的干净代码是另一个人的意大利面条代码。一个人的简单是另一个人的 Rube Goldberg 实现。在 Stack Overflow 的案例中,请关注 objective 指标,而不是 主观 指标。如果它有效,那么它就足够干净和简单了。

标签: python functional-programming documentation-generation docstring


【解决方案1】:

如果您需要文档字符串,我建议使用标准 Python 方式:

def pyfiles_by_length(directory):
    """
    Returns all Python files in `directory` sorted by length
    """
    return (directory > pipe
        | os.listdir
        | where(X.endswith('.py'))
        | sort_by(len).descending
        | (enumerate, X, 1)
        | foreach("{0}. {1}")
        | '\n'.join)

【讨论】:

  • 链接的github问题:github.com/0101/pipetools/issues/19
  • 这是一个很好的解决方案,但如果输入是 pandas 数据框,这将不起作用,因为它实现了 gt
  • 是的,这很不幸。在这种情况下,您必须在最后传递输入或分两步进行。但这仍然是任何文档工具最能理解的选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
相关资源
最近更新 更多