weirdness with list()

Grant Edwards grant.b.edwards at gmail.com
Mon Mar 1 09:10:55 EST 2021


On 2021-03-01, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> On 28/02/21 1:17 pm, Cameron Simpson wrote:
>> [its length in bytes] is presented via the object's __len__ method,
>
>> BUT... It also has a __iter__ value, which like any Box iterates over
>> the subboxes.
>
> You're misusing __len__ here. If an object is iterable and
> also has a __len__, its __len__ should return the number of
> items you would get if you iterated over it. Anything else
> is confusing and can lead to trouble, as you found here.

That was certainly my reaction. Can you imagine the confusion if len()
of a list returned the number of bytes required for srorage insttead
of the number of elements?

>> But is there a cleaner way to do this?
>
> Yes. Give up on using __len__ to get the length in bytes,
> and provide another way to do that.





More information about the Python-list mailing list