Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are min and max listed as sequence operations?

Tags:

python

Python's documentation has a table with "Common Sequence Operations" that are "supported by most sequence types". It lists for example x in s, s[i], and len(s), which the sequence can support with methods __contains__, __getitem__ and __len__. But it also lists min(s) and max(s), and I don't understand why. Those two work on any iterable, I don't see anything special about them in relation to sequences. There are no __min__ and __max__ or any other ways to truly support them, are there? And if there were, I'd expect max(range(10**8)) to give me the result instantly, not take several seconds. Just like 10**20 in range(10**30) does. And if min and max are just there to showcase built-in functions, I'd rather expect reversed to be listed, as that really has something to do with sequences (it works on every sequence, but not on every iterable).

So am I overlooking something? Or did __min__ and __max__ or some other way to truly support min and max exist in previous Python versions, and the table wasn't updated? Or is there some other good reason to list them there? I'm confused.

The first paragraph in that section even says:

The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

That sounds like people writing custom sequence types are somehow expected to implement them. That makes no sense to me unless there's an actual way to implement them.

like image 832
Kelly Bundy Avatar asked Oct 26 '22 17:10

Kelly Bundy


1 Answers

It looks like a documentation bug, the original commit for this was made in 1998. Probably the idea was to list all operations user can perform on sequences, not necessarily override them.

reversed on the other hand was added in 2003.

When the The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types part was added either the min/max functions should have been removed from the table to prevent such confusion(as there are no dunder methods available yet to override the behaviour of these two built-in functions) or the wording should've been improved.

like image 89
Ashwini Chaudhary Avatar answered Oct 29 '22 23:10

Ashwini Chaudhary