map strangeness

Sami Hangaslammi sami.hangaslammi.spam.trap at yomimedia.fi
Fri Aug 18 06:44:57 EDT 2000


Is there any specific reason why the build-in function "map" needs to have
__len__ defined for instances that emulate sequences? It doesn't seem to use
the value at all, for example the following works:

|
|class Fib:
|    def __init__(self, max=None):
|        self.max = max
|        self.current = 1
|        self.prev = 0
|
|    def __getitem__(self, i):
|        if (max is not None) and self.current > self.max:
|            raise IndexError
|        x = self.current
|        self.current, self.prev = x + self.prev, x
|        return x
|
|    def __len__(self):
|        return 0
|
>> map(lambda x: x*2, Fib(10))
[2, 2, 4, 6, 10, 16]

But without the "dummy" __len__ function you get:
AttributeError: 'Fib' instance has no attribute '__len__'

The same holds true also for 'filter', but 'reduce' seems to work without
__len__.

Using Python 1.6b1





More information about the Python-list mailing list