-1

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'
TylerH
  • 20,799
  • 66
  • 75
  • 101
Hamza Zubair
  • 1,232
  • 13
  • 21
  • @TylerH "clean and simple" is not irrelevant, if you are talking about a team communicating code over a large code base. – Hamza Zubair Jul 16 '21 at 03:00
  • 1
    Yes, it is, because it's opinion-based, and such metrics are not on-topic ones to ask about here. One person's clean code is another person's spaghetti code. One person's simple is another person's Rube Goldberg implementation. Concern yourself with *objective* metrics, not *subjective* ones, in Stack Overflow's case. If it *works*, then it's clean enough and simple enough. – TylerH Jul 19 '21 at 14:17

1 Answers1

2

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)
0101
  • 91
  • 4
  • linked github issue: https://github.com/0101/pipetools/issues/19 – Hamza Zubair Jul 15 '21 at 16:32
  • This is a good solution, except this will not work if the input is a pandas dataframe, because it has a __gt__ implemented. – Hamza Zubair Jul 16 '21 at 03:03
  • 1
    Yeah, that's unfortunate. In that case you have to pass the input at the end or make it in 2 steps. But this is still the option that will be best understood by any documentation tools. – 0101 Jul 17 '21 at 13:30