Velocity Reviews - Computer Hardware Reviews

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

Reply
Thread Tools

Implicit conversion to boolean in if and while statements

 
 
Steven D'Aprano
Guest
Posts: n/a
 
      07-17-2012
On Sun, 15 Jul 2012 10:56:57 +0000, Steven D'Aprano wrote:

> On Sun, 15 Jul 2012 03:34:46 -0500, Andrew Berg wrote:
>
>> This has probably been discussed before,

>
> By the hoary hosts of Hoggoth, has it ever!


Dammit this topic is a tar-baby.





--
Steven
 
Reply With Quote
 
 
 
 
Andrew Berg
Guest
Posts: n/a
 
      07-17-2012
On 7/16/2012 11:39 PM, Steven D'Aprano wrote:
> If you need three (or four, or fifty)
> distinguishable states, then obviously boolean context will not solve
> your problem. I never said it would.

That is the impression I got from this statement:

> How you interpret some_variable = None depends on what some_variable
> represents. If some_variable represents "number of jelly beans in a jar",
> then that should be 0 if there is no jar.

But I guess you misunderstood (or were just picking at) the example.

Of course I can (and do) explicitly use "if x is not None" when testing
for None, but I don't want a bug being obscured because "if x" accepts
an erroneous value that it interprets as truthy or falsey. I could be
explicit when testing for things other than None, but apparently that's
un-Pythonic.

To put it in duck-typing terms, why should everything have to quack like
True or False? Sure, I can see why 1 quacks like True or [] quacks like
False, but I don't see why say, a Logger or function should quack like
either. Should a Thread object be True if it's been started and False
otherwise?

If it truly is about something vs. nothing, why is a NameError (or
AttributeError) raised when testing with an undefined variable? Being
undefined quacks like nothing, doesn't it?
--
CPython 3.3.0b1 | Windows NT 6.1.7601.17803
 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      07-17-2012
On Mon, 16 Jul 2012 11:13:33 -0700, Ethan Furman wrote:

> Steven D'Aprano wrote:
>> On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly wrote:
>>> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano wrote:
>>>> (For the record, I can only think of one trap for the unwary: time
>>>> objects are false at *exactly* midnight.)
> >>
>>> Ugh, that's irritating. I can't think of any scenario where I would
>>> ever want the semantics "if timeval (is not midnight):".

>>
>> Yes, it is a genuine gotcha. Time values are numbers, and zero is
>> falsey, so midnight is falsey even though it shouldn't be.
>>
>> There's no good solution here, since we have a conflict between
>> treating time values as time values ("midnight is nothing special") and
>> as numbers ("midnight == 0 which is falsey").

>
> --> import datetime
> --> mn = datetime.time(0)
> --> mn
> datetime.time(0, 0)
> --> mn == 0
> False
>
> Apparently, midnight does not equal zero.


My mistake.



--
Steven
 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      07-17-2012
On Tue, 17 Jul 2012 00:18:28 -0400, Devin Jeanpierre wrote:

> On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano
> <(E-Mail Removed)> wrote:
>> 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.

>
> Your entire reply is predicated on this idea that I was talking about
> writing classes with this extra "isempty" method.
>
> No. I was talking about having "isempty" be part of the collection
> interface, and eliminating polymorphic bool conversion.


It already is part of the collection interface: it is spelled __nonzero__
(Python 2) or __bool__ (Python 3), and like all dunder methods, it is
called automatically for you when you use the right syntax:

# do this
x = n - len(y)
if x and y:
...

# don't do this
x = n.__sub__(y.__len__())
if x.__nonzero__() and y.__nonzero__():
...


--
Steven
 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      07-17-2012
On Tue, 17 Jul 2012 00:19:48 -0500, Andrew Berg wrote:

> To put it in duck-typing terms, why should everything have to quack like
> True or False? Sure, I can see why 1 quacks like True or [] quacks like
> False, but I don't see why say, a Logger or function should quack like
> either.


The default behaviour is that every object is something, hence true-like,
unless explicitly coded to be treated as false-like. Since both loggers
and functions are objects, they are true-like unless the default is
overridden.

If you don't like that simple, consistent model for truthiness, feel free
to design your own language with a different model. Or you can use any
one of the dozens of other existing languages which do what you want.


> Should a Thread object be True if it's been started and False
> otherwise?


If you, the Thread class author, want it to be, you can make it so.


> If it truly is about something vs. nothing, why is a NameError (or
> AttributeError) raised when testing with an undefined variable? Being
> undefined quacks like nothing, doesn't it?


Not really. It doesn't quack like anything.


Are you suggesting that if x doesn't exist, you want this behaviour?


>>> del x # make sure x doesn't exist
>>> if x: print('cheese')

.... else:
.... print('x is falsy')
.... print(x)
....
x is falsy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined


OH MAN, that would be SO AWESOME, we should like so do it!!!

(I'm being sarcastic, in case it's not obvious.)



--
Steven
 
Reply With Quote
 
John Nagle
Guest
Posts: n/a
 
      07-17-2012
On 7/15/2012 1:34 AM, Andrew Berg wrote:
> This has probably been discussed before, but why is there an implicit
> conversion to a boolean in if and while statements?
>
> if not None:
> print('hi')
> prints 'hi' since bool(None) is False.
>
> If this was discussed in a PEP, I would like a link to it. There are so
> many PEPs, and I wouldn't know which ones to look through.
>
> Converting 0 and 1 to False and True seems reasonable, but I don't see
> the point in converting other arbitrary values.


Because Boolean types were an afterthought in Python. See PEP 285.
If a language starts out with a Boolean type, it tends towards
Pascal/Ada/Java semantics in this area. If a language backs
into needing a Boolean type, as Python and C did, it tends to have
the somewhat weird semantics of a language which can't quite decide
what's a Boolean. C and C++ have the same problem, for exactly the
same reason - boolean types were an afterthought there, too.

John Nagle
 
Reply With Quote
 
Andrew Berg
Guest
Posts: n/a
 
      07-17-2012
On 7/17/2012 2:08 AM, Steven D'Aprano wrote:
> The default behaviour is that every object is something, hence true-like,
> unless explicitly coded to be treated as false-like. Since both loggers
> and functions are objects, they are true-like unless the default is
> overridden.

I am aware of the default behavior, but the reason for it still eludes me.

> Are you suggesting that if x doesn't exist, you want this behaviour?

I don't want that, but I am suggesting that it would be consistent with
the idea of "something or nothing".
--
CPython 3.3.0b1 | Windows NT 6.1.7601.17803
 
Reply With Quote
 
Chris Angelico
Guest
Posts: n/a
 
      07-17-2012
On Tue, Jul 17, 2012 at 6:23 PM, Andrew Berg <(E-Mail Removed)> wrote:
> On 7/17/2012 2:08 AM, Steven D'Aprano wrote:
>> The default behaviour is that every object is something, hence true-like,
>> unless explicitly coded to be treated as false-like. Since both loggers
>> and functions are objects, they are true-like unless the default is
>> overridden.

> I am aware of the default behavior, but the reason for it still eludes me.


There has to be something. This way, you can use None in place of any
object, in the same way that a null pointer would be used in C; any
object is true, None isn't. What other default makes more sense?

ChrisA
 
Reply With Quote
 
Devin Jeanpierre
Guest
Posts: n/a
 
      07-17-2012
On Tue, Jul 17, 2012 at 2:25 AM, Steven D'Aprano
<(E-Mail Removed)> wrote:
> It already is part of the collection interface: it is spelled __nonzero__
> (Python 2) or __bool__ (Python 3), and like all dunder methods, it is
> called automatically for you when you use the right syntax:


You're still ignoring what I actually said.

-- Devin
 
Reply With Quote
 
Ethan Furman
Guest
Posts: n/a
 
      07-17-2012
Andrew Berg wrote:
> To put it in duck-typing terms, why should everything have to quack like
> True or False? Sure, I can see why 1 quacks like True or [] quacks like
> False, but I don't see why say, a Logger or function should quack like
> either. Should a Thread object be True if it's been started and False
> otherwise?


True and False are red herrings. It is more appropriate to think that
True quacks like something and False like nothing than the other way 'round.

Maybe some examples from my own code will help:

DbfTable --> True if any records in table, False otherwise

DbfIndex --> True if any records in index, False otherwise

DbfList --> True if any records in list, False otherwise

DbfDate --> True if a date, False otherwise (could be eight spaces
instead of a real date)

DbfDateTime --> True if a datetime, False otherwise

DbfRecord --> True always

DbfRecordTemplate --> True always

DbfRecordVaporware --> False always

While I could have DbfRecord be False if, for example, it had no data
stored in it, I have no use case for that scenario so haven't bothered.
Also, at this point I am using the distinction of True/False with
regards to records to determine if I have a real record (True means a
record/template I can read/write, False means I don't).


> If it truly is about something vs. nothing, why is a NameError (or
> AttributeError) raised when testing with an undefined variable? Being
> undefined quacks like nothing, doesn't it?


It's about /representing/ something vs. nothing. An undefined name isn't
representing anything (except a bug, of course .

~Ethan~
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Implicit conversion to boolean in if and while statements Stefan Behnel Python 0 07-15-2012 09:17 AM
Re: Implicit conversion to boolean in if and while statements Chris Angelico Python 0 07-15-2012 08:47 AM
Subtle difference between boolean value and boolean comparison? Metre Meter Javascript 7 08-06-2010 08:40 PM
if statements and case statements questions John Crichton Ruby 6 07-12-2010 06:17 PM
difference between 'boolean' and 'java.lang.Boolean' J Leonard Java 4 01-19-2008 02:56 AM



Advertisments