Python documentation: repeated many times?

When documenting a Python function, I find more Pythonic to say:

def Foo(i): """i: An interable containing…""" 

... but not...

 def Foo(i): """i: A list of …""" 

When i really don't need to be a list . ( Foo will happily work with set , tuple , etc.). The problem is generators. Usually, generators allow only 1 iteration. Most functions are OK with generators or iterators that allow only one pass, but some of them are not.

For those functions that can't take generators / things that can only be repeated once, is there a clear, consistent Python term to say "a thing that can be repeated only once"?

The Python glossary for iterable and iterator seems to have "one time, but maybe more if you're lucky."

+6
source share
2 answers

I do not know the standard term for this, at least not out loud, but I think that “reusable iterative” will make sense if you need a short phrase.

In practice, it is usually possible to structure your function, so you do not need to iterate more than i more than once. In addition, you can create a list from iterable and then iterate over the list as many times as you want; or you can use itertools.tee to get several independent "copies" of the iterator. This allows you to receive the generator, even if you need to use it more than once.

+2
source

This probably has more to do with style and preference than anything else, but ... I have a different attitude to my documentation: I always write docstring according to the expected input in the context of the program .

Example: if I wrote a function that expects to go through the keys of a dictionary and ignore its values, I write:

 arg : a dictionary of... 

even if for e in arg: will work with other iterators. I decided to do this because, in the context of my code, I don’t care whether the function will still work ... I don’t care if anyone reading the documentation understands how this function is intended to be used.

On the other hand, if I write a utility function that can handle a wide range of design iterations, I can do one of these two ways:

  • indicate what exception will be under certain conditions [ex: "Raise TypeError if iterability cannot be repeated more than once"]
  • do some preprocessing of the arguments , which will make the function compatible with iterations "only once."

In other words, I try either to make my function strong enough to handle extreme cases, or to be very frank about its limitations .

Again: there is nothing wrong with what you want to do, but I think this is one of the cases where “ explicit is better than implicit ”: the documentation that mentions “reusable iteration” is definitively accurate, but the adjective can be easy missed.

NTN!

+1
source

Source: https://habr.com/ru/post/902615/


All Articles