LangWart: Method congestion from mutate multiplicty

Terry Reedy tjreedy at udel.edu
Sun Feb 10 09:39:21 CET 2013


While it is true that sorted(iterable) is essentially

def sorted(iterable):
   tem = list(iterable)
   tem.sort
   return tem

the body is not an expression and cannot be substituted in an 
expression. The need for the short form was thought common enough to be 
worth, *on balance*, a new builtin name. It is not surprising that not 
all agree.

Reversed(iterable) is more complicated because it returns an iterator, 
not a list, and looks for a class-specific __reversed__ method. I think 
it is more or less equivalent to the following:

def _rev_iter(seq, n):
   for i in range(n-1, -1, -1):
   # many people have trouble getting the range right
     yield seq[i]

def reversed(iterable):
   try:
     return iterable.__reversed__()
   except AttributeError:
     try:
       itlen = iterable.__len__
       iterable.__getitem__
       return _rev_iter(iterable, itlen)
     except AttributeError:
       raise TypeError("argument to reversed() must be a sequence")

Even if list mutation methods returned the list, which they do not and 
for good reason, reversed(it) is not the same as list(it).reverse(). So 
that part of the premise of this thread is wrong.

-- 
Terry Jan Reedy




More information about the Python-list mailing list