Attack a sacred Python Cow

Carl Banks pavlovevidence at gmail.com
Mon Jul 28 02:45:26 EDT 2008


On Jul 27, 5:14 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote:
> > On Jul 26, 5:07 pm, Terry Reedy <tjre... at udel.edu> wrote:
> >> Whether or not one should write 'if x' or 'if x != 0' [typo corrected]
> >> depends on whether one means the general 'if x is any non-null object
> >> for which bool(x) == True' or the specific 'if x is anything other than
> >> numeric zero'.  The two are not equivalent.  Ditto for the length
> >> example.
>
> > Can you think of any use cases for the former?  And I mean something
> > where it can't be boiled down to a simple explicit test for the sorts of
> > arguments you're expecting; something that really takes advantage of the
> > "all objects are either true or false" paradigm.
>
> But why do you need the explicit test?

I asked you first, buddy.


[snip attempt to reverse argument]
> > The best thing I can come up with out of my mind is cases where you want
> > to check for zero or an empty sequence, and you want to accept None as
> > an alternative negative as well.  But that's pretty weak.
>
> You might find it pretty weak, but I find it a wonderful, powerful
> feature.

Powerful?  You've got to be kidding me.  If I have a function

create_object(name)

where one creates an anonymous object by passing an empty string,
behold! now I can also create an anonymous object by passing None.
You call that powerful?  I call it simple convenience, and not
something that we'd suffer much for for not having.  But it's still
the one thing I can think of that can't be replaced by a simple
explicit test.


> I recently wrote a method that sequentially calls one function after
> another with the same argument, looking for the first function that
> claims a match by returning a non-false result. It looked something like
> this:
>
> def match(arg, *functions):
>     for func in functions:
>         if func(arg):
>             return func
>
> I wanted the function itself, not the result of calling the function. I
> didn't care what the result was, only that it was something (indicates a
> match) or nothing (no match). In one application, the functions might
> return integers or floats; in another they might return strings. In a
> third, they might return re match objects or None. I don't need to care,
> because my code doesn't make any assumptions about the type of the result.

Couldn't you write the function to return None on no match, then test
if func(arg) is None?  That way would seem a lot more natural to me.
As an added bonus, you don't have to return some sort of wrapped
object if suddenly you decide that you want to match a zero.

Sorry, can't give it credit for the use case I was asking for.  I want
something where "if x" will do but a simple explicit test won't.


Carl Bannks



More information about the Python-list mailing list