Boolean tests [was Re: Attack a sacred Python Cow]
modelnine at modelnine.org
Tue Jul 29 11:15:05 CEST 2008
Am Dienstag, 29. Juli 2008 10:37:45 schrieb Carl Banks:
> You keep bringing up this notion of "more complex with no benefit",
> which I'm simply not interested in talking about that at this time,
> and I won't respond to any of your points. I am seeking the answer to
> one question: whether "if x" can usefully do something a simple
> explicit test can't. Everyone already knows that "if x" requires
> fewer keystrokes and parses to fewer nodes.
Yes, there are quite a lot of use cases. Think of a polymorphic function,
where the input can be any object that implements the iterator protocol
(concerning base types, I'm thinking of strings, tuples, lists, dicts and
sets here, which are all iterable and yield a chain of singular values) and
you want to check whether the iterable object is empty or not for
"if x" uses the special interface method __nonzero__() if that's implemented
(which all of the above types implement as returning True iff the container
yields at least one value when iterated over, i.e., it isn't empty), and
falls back to a test for __len__() != 0, otherwise x is considered to be
Now, explicitly comparing x against the five "empty" values of the container
types I specified above would be broken design in such a function: when I
implement a container class myself, which implements the __iter__() and
__nonzero__() methods, I can directly use it with the polymorphic function I
wrote, and the special case for an empty container will work out of the box.
In the case of explicit comparisons, I have to modify the polymorphic
function to accept my container type in addition to those it already
processes to be able to special-case the empty container for my type.
I can't dig up a simple example from code I wrote quickly, but because of the
fact that explicit comparisons always hamper polymorphism (which might not be
needed initially, but you never know what comes up later, thinking of
reusability of components), I personally always stick to the idiom "if x"
rather than comparing it to an empty value, even when I'm sure that the type
of x is a singular type.
Additionally, IMHO "if x" is so much more readable than "if x != <something>".
Just my 2 (euro)cents.
More information about the Python-list