On 9/5/05, Stuart Bishop <[EMAIL PROTECTED]> wrote:
> Urgh... I hadn't noticed that in vocabularies before. I believe this has
> other side effects too, such as if I do list(mysource), Python calls
> mysource.__len__ (if it exists) to preallocate the list size. Wierd things
> can happen if your class lies about itself and breaks contracts.

That's not so weird at all; this is how __len__() is generally used in
Python.  sys.maxint is the recommended value to return if the sequence
length is undetermined (such as when it can only be determined as a
side effect of iteration) or when it would be prohibitively expensive
to compute.  The __len__() should normally only be used to provide a
hint, unless you know you have an instance of  a type that always
returns an accurate value (such as a list, tuple, or str).

The Python runtime handles this case; if you find any specific points
in Python that accept an iterable (which might not provide __len__()
in the general case) that don't handle not being able to get an
accurate length, you should file a bug report against Python with a
test that demonstrates the problem.

> Do you happen to know *why* the vocabularies needed this method, and if the
> callsites could be fixed to catch a NotImplementedError or similar?

I don't remember why specifically we thought this useful at the time. 
__len__() always returns an int because of the signature of the tp_len
C slot in Python's internal structures.


Fred L. Drake, Jr.    <fdrake at gmail.com>
Zope Corporation
Zope3-dev mailing list
Unsub: http://mail.zope.org/mailman/options/zope3-dev/archive%40mail-archive.com

Reply via email to