Velocity Reviews > Implicit conversion to boolean in if and while statements

# Implicit conversion to boolean in if and while statements

Ranting Rick
Guest
Posts: n/a

 07-16-2012
On Jul 15, 9:13*pm, Steven D'Aprano <steve
(E-Mail Removed)> wrote:

> I have just written a bunch of code with about two dozen examples similar
> to this:
>
> for item in (seq or []):
> * * do_something_with(item)
>
> iterates over seq if it is non-empty, or the empty list. Writing it like
> this would be more painful, more complex, less readable and less
> idiomatic:
>
> if seq is not None:
> * * for item in seq:
> * * * * do_something_with(item)
>
> not to mention completely unnecessary if you have already checked that
> seq is either None or a sequence, and not some other arbitrary value.

Short circuitry is a powerful tool! But why the heck would your
sequences ever be None? Are you using None as a default? And if so,
why not use an empty sequence instead ([], {}, "")?

Ranting Rick
Guest
Posts: n/a

 07-16-2012
On Jul 15, 9:15*pm, Devin Jeanpierre <(E-Mail Removed)> wrote:

> For example, instead of "if stack:" or "if bool(stack):", we could use
> "if stack.isempty():". This line tells us explicitly that stack is a
> container. Or instead of "if dist:" or "if bool(dist):" we could use
> "if dist == 0:". This tells us explicitly that stack is a number.
> Supposedly this makes it easier to read code. It certainly reads more
> like English!

Yes, but this approach involves adding new "value testing" methods to
every object.

Whilst these specific methods would probably inject more comprehension
than using bool, i believe the bool function can handle this problem
better due to its monolithic and generic nature. No need to memorize
which method is needed for strings, or integers, or lists, etc... just
use bool and everything works. As for the semantics, we should let the
object decide how to respond to a __bool__() request.

But what's the point of having a bool function if we refuse to use it
correctly? We force str, int, and float conversion all day, but not
the bool? Where is the consistency? Where is the bool!?

Chris Angelico
Guest
Posts: n/a

 07-16-2012
On Mon, Jul 16, 2012 at 12:41 PM, Ranting Rick
<(E-Mail Removed)> wrote:
> On Jul 15, 9:13 pm, Steven D'Aprano <steve
> (E-Mail Removed)> wrote:
>
>> I have just written a bunch of code with about two dozen examples similar
>> to this:
>>
>> for item in (seq or []):
>> do_something_with(item)

>
> Short circuitry is a powerful tool! But why the heck would your
> sequences ever be None? Are you using None as a default? And if so,
> why not use an empty sequence instead ([], {}, "")?

Function default arguments spring to mind, especially if the list will
be mutated afterwards.

ChrisA

Steven D'Aprano
Guest
Posts: n/a

 07-16-2012
On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote:

> If HOWEVER we want to "truth test" an object (as in: "if obj") we should
> be FORCED to use the bool! Why? Because explicit is better than implicit

And this is why Rick always writes code like:

integer_value_three = int(1) + int(2)
assert (int(integer_value_three) == \
int(3) is True) is True, str("arithmetic failed")
list_containing_three_values_which_are_all_integer s_but_might_later_have_more_or_fewer_values_or_oth er_types = list([1, 2, integer_value_three])

because you can never have too much explicitness. Who wouldn't want

> and readability counts if we want to create maintainable code bases!

Yes you, Rick, are correct, that is to say not wrong, that readability,
that is to say the quality of ease of reading the text in question,
counts, that is to say that it matters to people who care about ease of
reading, when our motivation is to create, that is to say write,
maintainable code bases, that is to say unified collections of code which
can have software errors fixed and new features added with relatively
small amounts of effort on behalf of the human programmer.

And that, the reason given in the sentence above, is the reason that we,
collectively all programmers, should prefer to be explicit, not merely
conveying meaning by implication about everything we, collectively all
programmers, write, including typing, use of speech-recognition software,
or any future technological process by which text or program code or both
is transcribed from the idea of the human person to a permanent form
recorded where other people, or non-human sentient beings, can read or
otherwise gain access to it for the purpose of understanding the content
of the test or program code or both.

--
Steven

Chris Angelico
Guest
Posts: n/a

 07-16-2012
On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano
<(E-Mail Removed)> wrote:
> And that, the reason given in the sentence above, is the reason that we,
> collectively all programmers, should prefer to be explicit, not merely
> conveying meaning by implication about everything we, collectively all
> programmers, write, including typing, use of speech-recognition software,
> or any future technological process by which text or program code or both
> is transcribed from the idea of the human person to a permanent form
> recorded where other people, or non-human sentient beings, can read or
> otherwise gain access to it for the purpose of understanding the content
> of the test or program code or both.

I'd rather be booled in oil.

ChrisA
*ducks for cover*

Ranting Rick
Guest
Posts: n/a

 07-16-2012
On Jul 15, 9:58*pm, Steven D'Aprano <steve
(E-Mail Removed)> wrote:
> On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote:
> > If HOWEVER we want to "truth test" an object (as in: "if obj") we should
> > be FORCED to use the bool! Why? Because explicit is better than implicit

>
> And this is why Rick always writes code like:

....

Traceback (most recent quip last):
Author: "<DeAprano>", line 7, in <post>

Steven D'Aprano
Guest
Posts: n/a

 07-16-2012
On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote:

> For example, instead of "if stack:" or "if bool(stack):", we could use
> "if stack.isempty():". This line tells us explicitly that stack is a
> container.

isempty is not a container method.

py> container = []
py> container.isempty()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'isempty'

Your code tells us explicitly that stack is expected to be an object with
an isempty() method. What does that mean? Who knows?

calories = macdonalds.fries('large')
calories.isempty()
=> returns True

When you want to write polymorphic code to handle your stack, you end up
doing something like this:

if isinstance(stack, MyStackClass):
flag = stack.isempty()
else:
try:
# list, collections.deque, many others
flag = len(stack) == 0
except AttributeError:
try:
if sys.version < '3':
flag = not stack.__nonzero__()
else:
flag = not stack.__bool__()
except AttributeError:
# Is this even possible in Python 3?
flag = False # I guess...
# If we get here, flag is true if stack is empty.
if flag:
...

Yeah, explicit is *so much better* for readability. Can't you just *feel*
how much more readable all those irrelevant implementation details are?

If you're smart, you wrap all of the above in a function:

def isempty(stack):
# blah blah as above

But if you're *really* smart, you write to the interface and let Python
take care of the polymorphic details for you:

if not stack:
...

(Assuming that stack defines __nonzero__ or __len__ correctly, which it
better if it claims to be a container.)

It boggles my mind that people who are perfectly happy to program to an
interface or protocol when it comes to (say) iterables, numbers or even
big complex classes with dozens of methods, suddenly freak out at the
thought that you can say "if obj" and obj is duck-typed.

There's a distinct lack of concrete, actual problems from duck-typing
bools, and a heavy over-abundance of strongly-held opinion that such a
thing is self-evidently wrong.

> As far as I know, the only use of having a polymorphic boolean
> conversion is reducing the amount of typing we do.

The same could be said about *every* polymorphic function.

The benefit is not just because you don't wear out your keyboard as fast.
The benefit is the same for all other polymorphic code: it lets you write
better code faster with fewer bugs and less need for unnecessary type
restrictions.

If there are a few corner cases where you actually *need* to restrict the
type of your flags to a actual bool, well, Python gives you the tools to
do so. Just as you can restrict the type of a sequence to exactly a list
and nothing else, or a number as exactly a float and nothing else. Just
do your type tests before you start operating on the object, and reject
anything that doesn't match what you want.

But that should be the exception, not the rule.

> Generally objects
> with otherwise different interfaces are not interchangeable just because
> they can be converted to booleans, so you wouldn't lose much by being
> forced to explicitly convert to boolean with something
> interface-specific.

Until somebody writes an awesomely fast stack class in C and gives it an
is_empty() method instead of isempty, and your code can't use it because

--
Steven

Steven D'Aprano
Guest
Posts: n/a

 07-16-2012
On Sun, 15 Jul 2012 20:21:41 -0700, Ranting Rick wrote:

> On Jul 15, 9:58Â*pm, Steven D'Aprano <steve
> (E-Mail Removed)> wrote:
>> On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote:
>> > If HOWEVER we want to "truth test" an object (as in: "if obj") we
>> > should be FORCED to use the bool! Why? Because explicit is better
>> > than implicit

>>
>> And this is why Rick always writes code like:

> ...
>
> Traceback (most recent quip last):
> Author: "<DeAprano>", line 7, in <post>

Deary deary me Rick. Reductio ad adsurdum is not a fallacy. It is a
counter-argument to an argument or claim, by showing that the premise of
the original claim leads to an absurd conclusion.

You have claimed that we should always be explicit whenever we write. But
you do not actually live up to your own advice, because you can't: it is
absurd to try to be explicit about everything all the time. You have
misunderstood the purpose of the Zen of Python: it is not to claim that
everything should be explicit, but to avoid code that is hard to
understand because things which need to be explicit for clarity are
implied by other parts of your code.

(It's not like explicit and implicit are distinct -- everything depends
on something implicit, if only the meaning of the words you use to
describe it.)

It certainly doesn't mean that the semantics of Python the language must
be written out explicitly every time you use each feature.

for x in sequence: # Yes, implies that we iterate over the values

for loop variable named x in iterable sequence iterate over values and
assign the loop variable each time you go around the loop executing the
following block each time:
# No, since that tells us what we already know and just adds
# meaningless verbosity for the sake of faux "explicitness"

--
Steven

Ranting Rick
Guest
Posts: n/a

 07-16-2012
On Jul 15, 11:03*pm, Steven D'Aprano <steve
(E-Mail Removed)> wrote:
> On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote:

> It boggles my mind that people who are perfectly happy to program to an
> interface or protocol when it comes to (say) iterables, numbers or even
> big complex classes with dozens of methods, suddenly freak out at the
> thought that you can say "if obj" and obj is duck-typed.

"if obj" is in essence doing "if bool(obj)" behind the scenes. My
question is: Why hide such valuable information from the reader? It's
obvious that "if bool(obj)" will return a boolean; whereas "if obj" is
ambiguous.

> There's a distinct lack of concrete, actual problems from duck-typing
> bools, and a heavy over-abundance of strongly-held opinion that such a
> thing is self-evidently wrong.

If the multitudes of misunderstandings from "if obj" on this list have
not convinced you yet, then i lack the energy to educate you!

> > As far as I know, the only use of having a polymorphic boolean
> > conversion is reducing the amount of typing we do.

>
> The same could be said about *every* polymorphic function.

For which "bool" IS!

Wikipedia to the rescue:
"""In computer science, polymorphism is a programming language feature
that allows values of different data types to be handled using a
uniform interface. The concept of parametric polymorphism applies to
both data types and functions. A function that can evaluate to or be
applied to values of different types is known as a polymorphic
function."""

bool("a") -> True
bool(0) -> False
bool([1,2,3]) -> True
bool(True) -> True

> The benefit is not just because you don't wear out your keyboard as fast.
> The benefit is the same for all other polymorphic code: it lets you write
> better code faster with fewer bugs and less need for unnecessary type
> restrictions.

There are NO type restrictions for bool.

> If there are a few corner cases where you actually *need* to restrict the
> type of your flags to a actual bool, well, Python gives you the tools to
> do so.

Yes, the bool()

Ranting Rick
Guest
Posts: n/a

 07-16-2012
On Jul 15, 11:20*pm, Steven D'Aprano <steve
(E-Mail Removed)> wrote:

> (It's not like explicit and implicit are distinct -- everything depends
> on something implicit, if only the meaning of the words you use to
> describe it.)
>
> It certainly doesn't mean that the semantics of Python the language must
> be written out explicitly every time you use each feature.

Of course not. Don't be ridiculous.

> for x in sequence: [...]

This syntax is explicit *enough*. We don't need to be any more
explicit.

But if you are going to argue that "if obj" is *explicit enough*, then
apply your argument consistently to "String"+1.75 also. Why must we be
explicit about string conversion BUT not boolean conversion? Can you
reduce this to the absurd? Or will you just choose to ignore this
valid point?