Boolean tests [was Re: Attack a sacred Python Cow]

Erik Max Francis max at alcyone.com
Tue Jul 29 16:08:26 EDT 2008


Carl Banks wrote:
> On Jul 29, 1:30 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
>> On Jul 29, 5:15 am, Heiko Wundram <modeln... at modelnine.org> 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?
> 
> And, in case it wasn't obvious, the way to demonstrate that "if x"
> improves polymorphism relative to simple explicit tests would be
> posting an example where "if x" works but a simple explicit test
> doesn't.  So don't accuse me of changing the question on you: it's the
> same question.

It's pretty elementary, and people thought just describing the issue of 
polymorphism and duck-typing was sufficient to explain it.  Since it 
apparently isn't:

Let's say you come up with some kind of custom sequence class.  You want 
to act like any native sequence type (list, tuple, array, string, etc.) 
in all reasonable ways (length testing, iteration, indexing, etc.) so 
that it can be used in place of these things in code that doesn't 
require explicit types.  You know, standard polymorphism and duck-typing.

So you want a test for whether your custom sequence isn't empty.  To 
create an "simple, explicit test" would be defined an `isntEmpty` method 
that you can call, like so:

	if myObject.isntEmpty():
	    # then do something

However, this wouldn't be polymorphic since now someone would have to 
call a "simple, explicit test" that doesn't exist on all the other 
sequence-like objects.  Therefore, you've broken polymorphism.

The solution is to override the `__nonzero__` method so that you can use 
Boolean testing, just like all the other sequence-like objects:

	if myObject:
	    # then do the same thing

Now people who use your custom sequence type don't have to write special 
code, and code written to deal with sequences using duck typing (which 
is typically nearly all Python code) don't have to know anything special 
about your custom sequence class.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   Everything's gonna be all right / Everything's gonna be okay
    -- Sweetbox



More information about the Python-list mailing list