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

Donn Cave donn at u.washington.edu
Tue Jun 29 16:07:00 EDT 2004


In article <cbscnd$1sa$03$1 at news.t-online.com>,
 Peter Otten <__peter__ at web.de> wrote:
> Heiko Wundram wrote:
...
> > But, as always, documentation is better than guessing. ;)
> 
> No amount of documentation can heal an unintuitive API.
> The convention of using bool(o) as an abbreviation of o.isValid() for
> non-sequences and of len(o) != 0 for sequences seems natural to me. Mixing
> these two meanings or even adding "was this parameter provided" as a third
> one will result in highly ambiguous code that is bound to break.

I agree, but I think part of the problem is trying to milk too
much from all of these features.

The time to implement __nonzero__, __getitem__ etc.  is when
there's a clear need for them, like an application context
where this polymorphism is needed to make things work.  If you
do it because you think it looks nicer, don't complain when
it breaks things because you brought it on yourself with this
fuzzy thinking.  (Using "you" in the generic sense.)

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list