Suggestions for good programming practices?

Mark McEahern marklists at mceahern.com
Mon Jun 24 17:31:14 EDT 2002


[David LeBlanc]
> I'm curious to know how this encourages polymorphism, and how making a
> conditional test implicit rather then explicit is good practice?

Your question reveals my lack of understanding and clarity.  Let me try
again:

If you compare to None with equality, your tests may fail for objects that
overload the comparison functions and don't anticipate other being None.  An
example I encountered was using Tim Peters' FixedPoint for currency values.
It doesn't make sense to do this:

	x = FixedPoint(None)

and yet that's what will happen if you try to do this:

	x = FixedPoint(1.00)
	...
	if x == None:

In other words, this raises an error.  I think the intention behind that
comparison is really to see whether x is None, is in the specific identity
sense.  This, of course, is contrary to my statement about if x being
preferable to if x is not None.

Anyway, I gave an example of why you might not want to use this, but maybe
it seems too convoluted:

	if x == None:

How do you choose between these:

	if x is None:

	if x:

The latter is what you'd use if you wanted to work with instances that
defined __nonzero__ and or __len__.  In other words, you don't really care
what the type of x is, nor whether it's identity is zero, just whether it
considers itself nonzero.

Is one more or less polymorphic than the other?  I don't really know.  But
it sure does sound good.

Cheers,

// mark

-






More information about the Python-list mailing list