class with __len__ member fools boolean usage "if x:" ; bad coding style?

Jeff Epler jepler at
Wed Jun 30 04:48:52 CEST 2004

> Am Dienstag, 29. Juni 2004 20:34 schrieb Peter Otten:
> > A __len__() without a __getitem__() method doesn't make sense to me. But
> > maybe your example is just too terse...

On Wed, Jun 30, 2004 at 12:53:15AM +0200, Heiko Wundram wrote:
> Why should you need a __getitem__() if you have __len__() defined? In my use 
> case, the ID (of a host/data-item, etc.) is not retrievable by single 
> character (that would make no sense), but the length of the ID is 
> significant, as it can signal important information as on the protocol to use 
> to contact the host, etc.

I agree with Herr Otten.  __len__ is intended to be implemented by
container objects.
If your object doesn't permit item access (o[i] or o[k]) then I think
people will be surprised to find that len(o) does not cause a TypeError.

Of course, you're permitted to write any program you like, and Python
will even execute some of them and give results that please you.  You're
not required to write only programs that don't surprise anybody.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list