On Jul 29, 3:43 pm, "Heiko Wundram" <[EMAIL PROTECTED]> wrote: > Am 29.07.2008, 18:30 Uhr, schrieb Carl Banks <[EMAIL PROTECTED]>: > > > On Jul 29, 5:15 am, Heiko Wundram <[EMAIL PROTECTED]> wrote: > >> I can't dig up a simple example from code I wrote quickly, but because > >> of the > >> fact that explicit comparisons always hamper polymorphism > > > I'm not going to take your word for it. Do you have code that > > demonstrates how "if x" improves polymorphism relative to simple > > explicit tests? > > As I wrote in the second reply email I sent, check out my integer set > recipe on ASPN (and to save you the search: > http://code.activestate.com/recipes/466286/).
Couple points: 1. Any container type that returns a length that isn't exactly the number of elements in it is broken. 2. The need for __nonzero__ in this case depends on a limitation in the language. 3. On the other hand, I will concede that sometimes calculating len is a lot more expensive than determining emptiness, and at a basic level it's important to avoid these costs. You have found a practical use case for __nonzero__. However, I'd like to point out the contrasting example of numpy arrays. For numpy arrays, "if x" fails (it raises an exception) but "if len(x)!=0" succeeds. The only sane advice for dealing with nonconformant classes like numpy arrays or your interger set is to be wary of nonconformances and don't expect polymorphism to work all the time. So I guess I'll concede that in the occasional cases with nonconformant classes the "if x" might help increase polymorphism a little. (BTW: here's another little thing to think about: the "if x" is useful here only because there isn't an explicit way to test emptiness without len.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list