[Python-ideas] Suggested MapView object (Re: __len__() for map())
Terry Reedy
tjreedy at udel.edu
Tue Dec 11 13:41:32 EST 2018
On 12/11/2018 6:48 AM, E. Madison Bray wrote:
> The idea would be to now enhance the existing built-ins to restore at
> least some previously lost assumptions, at least in the relevant
> cases. To give an analogy, Python 3.0 replaced range() with
> (effectively) xrange(). This broken a lot of assumptions that the
> object returned by range(N) would work much like a list,
A range represents an arithmetic sequence. Any usage of range that
could be replaced by xrange, which is nearly all uses, made no
assumption broken by xrange. The basic assumption was and is that a
range/xrange could be repeatedly iterated. That this assumption was met
in the first case by returning a list was somewhat of an implementation
detail. In terms of mutability, a tuple would be have been better, as
range objects should not be mutable. (If [2,4,6] is mutated to [2,3,7],
it is no longer a range (arithmetic sequence).
> and Python 3.2 restored some of that list-like functionality
As I see it, xranges were unfinished as sequence objects and 3.2
finished the job. This included having the min() and max() builtins
calculate the min and max efficiently, as a human would, as the first or
last of the sequence, rather than uselessly iterating and comparing all
the items in the sequence.
A proper analogy to range would be a re-iterable mapview (or 'mapseq)
like what Steven D'Aprano proposes.
> ** I have a separate complaint that there's no great way, at the
> Python level, to define a class that is explicitly a "sequence" as
> opposed to a more general "mapping",
You mean like this?
>>> from collections.abc import Sequence as S
>>> isinstance((), S)
True
>>> isinstance([], S)
True
>>> isinstance(range(5), S)
True
>>> isinstance({}, S)
False
>>> isinstance(set(), S)
False
>>> class NItems(S):
def __init__(self, n, item):
self.len = n
self.item = item
def __getitem__(self, i): # missing index check
return self.item
def __len__(self):
>>> isinstance(NItems(2, 3), S)
True
--
Terry Jan Reedy
More information about the Python-ideas
mailing list