Search code examples
pythonfunctional-programmingdocumentation-generationdocstring

How to write docstrings for functions written in functional paradigm using pipetools


I use pipetools to write functions, which is a "functional plumbing library for python".

An example function (from their docs):

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

This is a function definition. How would we write docstrings for such a function

What I have tried:

  1. Comment before function (PRO: clean and simple. CON: will not work with documentation libraries)
# 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: works with documentation libraries, CON: not clean and simple)
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'

Solution

  • If you need a docstring, I would recommend using the standard Python way:

    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)