Message29050
| Author |
collinwinter |
| Recipients |
| Date |
2006年07月05日.15:16:06 |
| SpamBayes Score |
| Marked as misclassified |
| Message-id |
| In-reply-to |
| Content |
Logged In: YES
user_id=1344176
I wasn't just reviewing the docs; I came upon this while
re-implementing filter() in pure Python for a compatibility
module I'm working on. I discovered this particular
implementation detail when my naive implementation (as a
listcomp) didn't pass test_builtin.
My question is why filter() even cares about __len__, ie,
why it doesn't simply use the iterator protocol. This is
especially curious since filter() actively ignores the
iterator protocol when dealing with subclasses of str,
unicode and tuple:
>>> class badstr(str):
... def __len__(self):
... return 4
... def __getitem__(self, index):
... return "a"
... def __iter__(self):
... for i in range(5):
... yield "b"
...
>>> filter(None, badseq("cccc"))
aaaa
>>> [x for x in badseq("cccc") if x]
['b', 'b', 'b', 'b', 'b']
Ignore the difference in return types (which is expected),
these two do not do the same thing; filter() uses a
combination of __len__ and __getitem__ while the listcomp
version uses the iterator protocol.
Clearly, in this case, "is equivalent to" means "bears only
a superficial relationship to". |
|
History
|
|---|
| Date |
User |
Action |
Args |
| 2007年08月23日 14:41:07 | admin | link | issue1517509 messages |
| 2007年08月23日 14:41:07 | admin | create |
|