[Python-3000] callable()

Raymond Hettinger rhettinger at ewtllc.com
Fri Jul 21 18:06:36 CEST 2006


>>
>> > We should make a conscious decision whether we should make it a
>> > permanent feature or not.
>>
>> It sure simplified writing extensions.
>> And it provided a convenient guarantee that all sequences are iterable.
>> I don't see a downside to keeping it.
>
>
> Well, it will also make mappings pseudo-iterable; in Py3k I plan to
> completely get rid of the distinction between x[...] for mappings and
> for sequences, which exist in C but not at the Python level.
>
Since builtin dicts and dict subclasses will already be iterable, the 
mappings in question would be from user-defined classes with lookup 
behavior and but not providing an iterator:

   class C:
        '''This could be either a mapping or sequence
           so it would be foolish to wrap it with a SeqIter'''
        def __getitem__(self, k):
             return f(k)
        def __len__(self):
             return L

So, by default, iter(C()) will now raise a TypeError and provide earlier 
detection of an error rather than waiting for a potential KeyError 
during iteration.  And even if C was intended to be a sequence,  
list(C()) would raise a TypeError rather than risk a KeyError if C 
turned-out to be a mapping.

Since all of the builtin sequences will already define __iter__, they 
are unaffected by this change.  What is left are user-defined sequence 
classes or extensions with __getitem__ but not __iter__.  To make those 
iterable, the user would need to either modify the class (if possible) 
or provide a SeqIte- like wrapper:

    def SeqIter(s):
        try:
            for i in itertools.count():
                 yield s[i]
        except IndexError:
            return

   for elem in SeqIter(s): ...    # be explicit about looping over a 
generic sequence

   L = list(SeqIter(s))             # explicit wrapper to avoid a 
TypeError for generic sequences


Does that correctly recap your proposal, its motivitations, and its 
implications?



Raymond


More information about the Python-3000 mailing list