Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #25341 > unrolled thread

Implicit conversion to boolean in if and while statements

Started byAndrew Berg <bahamutzero8825@gmail.com>
First post2012-07-15 03:34 -0500
Last post2012-07-17 00:26 -0700
Articles 20 on this page of 74 — 17 participants

Back to article view | Back to comp.lang.python


Contents

  Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-15 03:34 -0500
    Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-15 10:56 +0000
      Re: Implicit conversion to boolean in if and while statements Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-15 10:19 -0600
        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2012-07-15 09:50 -0700
          Re: Implicit conversion to boolean in if and while statements Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-15 12:01 -0600
            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2012-07-15 11:56 -0700
              Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-16 07:53 +1000
                Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 18:21 -0700
                  Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-16 11:51 +1000
                    Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 19:31 -0700
                      Re: Implicit conversion to boolean in if and while statements Albert van der Horst <albert@spenarnc.xs4all.nl> - 2012-07-16 17:57 +0000
                        Re: Implicit conversion to boolean in if and while statements Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-07-17 00:44 -0400
                  Re: Implicit conversion to boolean in if and while statements Devin Jeanpierre <jeanpierreda@gmail.com> - 2012-07-15 22:15 -0400
                    Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 19:58 -0700
                    Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 04:03 +0000
                      Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 21:53 -0700
                        Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-16 15:57 +1000
                        Re: Implicit conversion to boolean in if and while statements alex23 <wuwei23@gmail.com> - 2012-07-16 00:21 -0700
                      Re: Implicit conversion to boolean in if and while statements Devin Jeanpierre <jeanpierreda@gmail.com> - 2012-07-17 00:18 -0400
                        Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 06:25 +0000
                          Re: Implicit conversion to boolean in if and while statements Devin Jeanpierre <jeanpierreda@gmail.com> - 2012-07-17 05:38 -0400
                  Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 02:58 +0000
                    Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-16 13:05 +1000
                    Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 20:21 -0700
                      Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 04:20 +0000
                        Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 22:03 -0700
                          Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-16 16:00 +1000
                          Re: Implicit conversion to boolean in if and while statements alex23 <wuwei23@gmail.com> - 2012-07-16 00:27 -0700
                          Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 07:52 +0000
                          Re: Implicit conversion to boolean in if and while statements Laszlo Nagy <gandalf@shopzeus.com> - 2012-07-16 23:26 +0200
                        Re: Implicit conversion to boolean in if and while statements Laszlo Nagy <gandalf@shopzeus.com> - 2012-07-16 23:17 +0200
                    Re: Implicit conversion to boolean in if and while statements Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-07-16 07:30 +0100
                    Re: Implicit conversion to boolean in if and while statements Albert van der Horst <albert@spenarnc.xs4all.nl> - 2012-07-16 18:03 +0000
            Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2012-07-15 11:56 -0700
          Re: Implicit conversion to boolean in if and while statements Serhiy Storchaka <storchaka@gmail.com> - 2012-07-16 16:01 +0300
          Re: Implicit conversion to boolean in if and while statements rusi <rustompmody@gmail.com> - 2012-07-16 18:45 -0700
        Re: Implicit conversion to boolean in if and while statements Rick Johnson <rantingrickjohnson@gmail.com> - 2012-07-15 09:50 -0700
        Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 02:13 +0000
          Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-15 19:41 -0700
            Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-16 12:58 +1000
            Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 08:05 +0000
          Re: Implicit conversion to boolean in if and while statements Ethan Furman <ethan@stoneleaf.us> - 2012-07-16 11:13 -0700
            Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 06:14 +0000
      Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-15 12:02 -0500
        Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 02:38 +0000
          Re: Implicit conversion to boolean in if and while statements Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-07-16 13:28 -0400
            Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 01:12 +0000
              Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 01:13 +0000
          Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-16 15:33 -0500
          Re: Implicit conversion to boolean in if and while statements Ethan Furman <ethan@stoneleaf.us> - 2012-07-16 13:54 -0700
            Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 00:43 +0000
              Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-16 20:57 -0500
                Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 04:39 +0000
                  Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-17 00:19 -0500
                    Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 07:08 +0000
                      Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-17 03:23 -0500
                        Re: Implicit conversion to boolean in if and while statements alex23 <wuwei23@gmail.com> - 2012-07-17 18:35 -0700
                      Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-17 18:32 +1000
                      Re: Implicit conversion to boolean in if and while statements Laszlo Nagy <gandalf@shopzeus.com> - 2012-07-17 14:43 +0200
                      Re: Implicit conversion to boolean in if and while statements Laszlo Nagy <gandalf@shopzeus.com> - 2012-07-17 14:59 +0200
                      Re: Implicit conversion to boolean in if and while statements Terry Reedy <tjreedy@udel.edu> - 2012-07-17 13:57 -0400
                  Re: Implicit conversion to boolean in if and while statements Ethan Furman <ethan@stoneleaf.us> - 2012-07-17 05:35 -0700
              Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-17 12:13 +1000
      Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-15 12:16 -0500
      Re: Implicit conversion to boolean in if and while statements Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-15 11:45 -0600
      Re: Implicit conversion to boolean in if and while statements Terry Reedy <tjreedy@udel.edu> - 2012-07-15 16:09 -0400
      Re: Implicit conversion to boolean in if and while statements Terry Reedy <tjreedy@udel.edu> - 2012-07-15 16:28 -0400
      Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-16 20:22 -0500
        Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 04:11 +0000
          Re: Implicit conversion to boolean in if and while statements Ranting Rick <rantingrickjohnson@gmail.com> - 2012-07-16 21:18 -0700
            Re: Implicit conversion to boolean in if and while statements Chris Angelico <rosuav@gmail.com> - 2012-07-17 14:24 +1000
          Re: Implicit conversion to boolean in if and while statements Andrew Berg <bahamutzero8825@gmail.com> - 2012-07-16 23:44 -0500
      Re: Implicit conversion to boolean in if and while statements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-17 04:47 +0000
    Re: Implicit conversion to boolean in if and while statements John Nagle <nagle@animats.com> - 2012-07-17 00:26 -0700

Page 1 of 4  [1] 2 3 4  Next page →


#25341 — Implicit conversion to boolean in if and while statements

FromAndrew Berg <bahamutzero8825@gmail.com>
Date2012-07-15 03:34 -0500
SubjectImplicit conversion to boolean in if and while statements
Message-ID<mailman.2132.1342341291.4697.python-list@python.org>
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.

-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803

[toc] | [next] | [standalone]


#25346

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-15 10:56 +0000
Message-ID<5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com>
In reply to#25341
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!

> but why is there an implicit
> conversion to a boolean in if and while statements?

It's nothing to do with if and while. All Python objects are duck-typed 
as bools.

1) It's generally part of the duck-typing philosophy. If an object quacks 
like a bool, why not treat it as a bool?

2) It's useful and convenient for short-circuit boolean expressions such 
as any(), all(), and various things like:

    for x in mylist or []: 
        ...

is better than:

    if mylist is not None:
        for x in mylist: 
            ...

3) Rather than distinguishing "true" from "false", a more useful 
dichotomy is between "something" and "nothing". Python includes a number 
of ways of spelling "nothing" of various types, such as:

    None, 0, 0.0, '', [], {}, set()

and nearly everything else is "something".

4) Other languages such as Ruby, Javascript, PHP, Clojure and others also 
distinguish between true-like and false-like ("truthy" and "falsey") 
values. Although some of them have made some pretty weird and arbitrary 
choices for what counts as true-like and false-like, without Python's 
general principle that "nothing" values should be false.

(E.g. Javascript considers Boolean(false) to be a true value!!!)

5) Prior to Python 2.2, there was no bool type and no True and False 
values. In fact, here is an impassioned plea from an educator begging 
Guido not to introduce True and False to the language, because duck-typed 
truthy/falsey values are *so much better*.

http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360?hl=en

Sadly, or happily, Python did grow True and False values, but the 
fundamental distinction between something and nothing still exists.

(For the record, I can only think of one trap for the unwary: time 
objects are false at *exactly* midnight.)


-- 
Steven

[toc] | [prev] | [next] | [standalone]


#25354

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-07-15 10:19 -0600
Message-ID<mailman.2141.1342369188.4697.python-list@python.org>
In reply to#25346
On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> 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):".  This
reinforces the point that if you only want to test whether you have
None, you should use "is not None" rather than relying on __bool__.

[toc] | [prev] | [next] | [standalone]


#25357

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2012-07-15 09:50 -0700
Message-ID<7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com>
In reply to#25354
On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote:
> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
> <steve+comp.lang.python@pearwood.info> 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):".  This
> reinforces the point that if you only want to test whether you have
> None, you should use "is not None" rather than relying on __bool__.

I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax issue. Consider this:

## EXAMPLE A ##
py> if money:
...     do_something()

The syntax "if money" implies we are testing/measuring some attribute of "money", but what exactly about money are we testing/measuring? The problem lies in the syntax. To understand this syntax, we must first interpret what *IF* means, and we should *NEVER* need to interpret such a well defined word as *IF*! This syntax is far too opaque. Consider the alternative:

## EXAMPLE B ##
py> if bool(money):
...     do_something()

Now we have a hint. Even if we don't understand the inner workings of the "bool" function, we *do* understand that the statement "bool(money)" *must* return True or the block *will not* execute. 

We must NEVER present "if" in such confusing manner as ExampleA. I believe Guido made a grave mistake allowing this syntax to flourish. His intentions where noble, to save people a few keystrokes, but all he accomplished was to pave a road directly into hell. 

 "Explict is better than Implict"

[toc] | [prev] | [next] | [standalone]


#25364

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-07-15 12:01 -0600
Message-ID<mailman.2148.1342375350.4697.python-list@python.org>
In reply to#25357
On Sun, Jul 15, 2012 at 10:50 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax issue. Consider this:
>
> ## EXAMPLE A ##
> py> if money:
> ...     do_something()
>
> The syntax "if money" implies we are testing/measuring some attribute of "money", but what exactly about money are we testing/measuring? The problem lies in the syntax. To understand this syntax, we must first interpret what *IF* means, and we should *NEVER* need to interpret such a well defined word as *IF*! This syntax is far too opaque. Consider the alternative:
>
> ## EXAMPLE B ##
> py> if bool(money):
> ...     do_something()
>
> Now we have a hint. Even if we don't understand the inner workings of the "bool" function, we *do* understand that the statement "bool(money)" *must* return True or the block *will not* execute.

So now instead of having to understand how "if" handles arbitrary
values, we have to understand how "bool" handles arbitrary values.
How is that an improvement?

What should "if" do if presented a value that isn't True or False?
Raise a TypeError?

Next thing we know, people get so used to wrapping everything they
present to "if" in a "bool()" call, that they start writing silly
things like "if bool(x == 7)" and "if bool(isinstance(x, int))".  Why?
 Because it's faster and easier to automatically wrap the value in
"bool" than it is to put in the effort to verify that the value will
always be a bool to begin with in order to avoid a useless and
annoying exception.  At the point that happens, the "bool()" is
effectively just part of the if syntax, and we're back to where we
started.

[toc] | [prev] | [next] | [standalone]


#25365

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2012-07-15 11:56 -0700
Message-ID<bbc44546-ffb7-4ff9-bd43-3bfa068df75f@googlegroups.com>
In reply to#25364
On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote:

> So now instead of having to understand how "if" handles arbitrary
> values, we have to understand how "bool" handles arbitrary values.
> How is that an improvement?

Because we are keeping the condition consistent. We are not relying on implicit resolution of an object's value based on some dark, esoteric and inconsistent rules that defy all normal logic.

> What should "if" do if presented a value that isn't True or False?
> Raise a TypeError?

YES! Because IT IS the author's responsibility to present a condition that evaluates to either True or False. Anything else would be ridiculously inconsistent.

> Next thing we know, people get so used to wrapping everything they
> present to "if" in a "bool()" call, that they start writing silly
> things like "if bool(x == 7)" and "if bool(isinstance(x, int))".  

We cannot prevent morons from doing stupid things. "x==7" IS an explicit statement that evaluates to either True or False. Likewise, isinstance(obj, type) is a function that evaluates to either True or False. Wrapping either example in a bool call is redundant and only obfuscates the meaning. True equals True and False equal False. Why do you need to test that truth?

The only time you will be forced to use the bool is when you are NOT using rich comparisons or NOT using truth testing functions in a condition. The following require NO bool function:

obj == obj -> bool
obj != obj -> bool
obj > obj -> bool
obj < obj -> bool
obj >= obj -> bool
obj <= obj -> bool
isinstance(obj, type) -> bool
callable(obj) -> bool
hasattr(obj, name) -> bool
issubclass(obj, name) -> bool
..along with any function that returns a bool

Whereas: 
"if obj" -> Some esoteric semantics that defies all logic!

> Why?
> Because it's faster and easier to automatically wrap the value in
> "bool" than it is to put in the effort to verify that the value will
> always be a bool to begin with in order to avoid a useless and
> annoying exception.  

No, because we want our code to be EXPLICIT and consistent! Remember, writing obfuscated code is easy, however, interpreting obfuscated code is difficult! A good measure of your programming skill is to see how easily your code is read by the majority. 

 """If it's difficult to explain, it's probably a bad idea""". 

"if blah" is difficult to explain, whereas "if bool(blah)" is not.   

> At the point that happens, the "bool()" is
> effectively just part of the if syntax, and we're back to where we
> started.

That's a ridiculous conclusion. See points above^^^

[toc] | [prev] | [next] | [standalone]


#25374

FromChris Angelico <rosuav@gmail.com>
Date2012-07-16 07:53 +1000
Message-ID<mailman.2154.1342389192.4697.python-list@python.org>
In reply to#25365
On Mon, Jul 16, 2012 at 4:56 AM, Rick Johnson
<rantingrickjohnson@gmail.com> wrote:
> On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote:
>
>> So now instead of having to understand how "if" handles arbitrary
>> values, we have to understand how "bool" handles arbitrary values.
>> How is that an improvement?
>
> Because we are keeping the condition consistent. We are not relying on implicit resolution of an object's value based on some dark, esoteric and inconsistent rules that defy all normal logic.
>
>> What should "if" do if presented a value that isn't True or False?
>> Raise a TypeError?
>
> YES! Because IT IS the author's responsibility to present a condition that evaluates to either True or False. Anything else would be ridiculously inconsistent.

Then the construct "if bool(some_condition):" is redundant. What
you've described is a viable system (REXX, for instance, demands that
an IF statement be given strictly either a 1 or a 0 (there's no True
and False values, but you're not allowed to use 527 as a True value,
it has to be 1)), but it's still redundant to attempt the cast. For
instance, this REXX function will logically negate a value twice, thus
forcing it to boolean:

bool: procedure
return \\arg(1)

But if it's given a non-bool, it'll just bomb, exactly the same as the
if statement would. So Ian's point still stands.

ChrisA

[toc] | [prev] | [next] | [standalone]


#25375

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 18:21 -0700
Message-ID<86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com>
In reply to#25374
On Jul 15, 4:53 pm, Chris Angelico <ros...@gmail.com> wrote:
> Then the construct "if bool(some_condition):" is redundant.

Wrong again, pay attention Chris!

It's ONLY redundant IF "some_condition" is a rich comparison: like
"(a==b)" OR a boolean function: like "callable(a)".

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 readability counts if we want to create maintainable code
bases!

if bool(obj) and a==b: # Correct!
if obj and a==b:       # Incorrect!

Both lines of code currently produce the same result because
"somebody" decided to give objects esoteric boolean values. Sure, we
saved a few key stokes in a condition, but sadly at the cost of
readability and consistency. I see no reason why choosing implicit
resolution is better than explicit resolution. Saving six keystrokes
is simply not enough!

Python's motto has always been "readability counts", and for that
reason, we should return to Explicit Boolean Resolution if we want to
adhere to those principals.

[toc] | [prev] | [next] | [standalone]


#25378

FromChris Angelico <rosuav@gmail.com>
Date2012-07-16 11:51 +1000
Message-ID<mailman.2157.1342403476.4697.python-list@python.org>
In reply to#25375
On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick
<rantingrickjohnson@gmail.com> 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 readability counts if we want to create maintainable code
> bases!
>
> if bool(obj) and a==b: # Correct!
> if obj and a==b:       # Incorrect!

That still doesn't answer the question of what bool(obj) should do if
obj is not a bool, and why if can't do the exact same thing, since if,
by definition, is looking for a boolean state selector.

ChrisA

[toc] | [prev] | [next] | [standalone]


#25383

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 19:31 -0700
Message-ID<b2971c4d-0769-4d03-a7b6-c527629a85c1@x39g2000yqx.googlegroups.com>
In reply to#25378
On Jul 15, 8:51 pm, Chris Angelico <ros...@gmail.com> wrote:
> On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick
>
> <rantingrickjohn...@gmail.com> 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 readability counts if we want to create maintainable code
> > bases!
>
> > if bool(obj) and a==b: # Correct!
> > if obj and a==b:       # Incorrect!
>
> That still doesn't answer the question of what bool(obj) should do if
> obj is not a bool, and why if can't do the exact same thing, since if,
> by definition, is looking for a boolean state selector.
>
> ChrisA

My point is no different than this example:

py> cost = 1.75
py> cost
1.75
py> 'Cost = ' + cost

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    'Cost = ' + cost
TypeError: cannot concatenate 'str' and 'float' objects
py> 'Cost = ' + str(cost)
'Cost = 1.75'

We DON'T want Python to silently convert "cost" to a string. What we
DO want is to force the author to use the str function thereby making
the conversion explicit.

Same with converting objects to bools.

We DON'T want "if" to magically convert a non-boolean into a boolean.
What we DO want is to force the author to use the bool function
thereby making the conversion explicit. By doing so we transform
confusion into comprehension. By doing so we maintain the principals
of readability counts.

[toc] | [prev] | [next] | [standalone]


#25428

FromAlbert van der Horst <albert@spenarnc.xs4all.nl>
Date2012-07-16 17:57 +0000
Message-ID<m79lw9.omd@spenarnc.xs4all.nl>
In reply to#25383
In article <b2971c4d-0769-4d03-a7b6-c527629a85c1@x39g2000yqx.googlegroups.com>,
Ranting Rick  <rantingrickjohnson@gmail.com> wrote:

>We DON'T want Python to silently convert "cost" to a string. What we
>DO want is to force the author to use the str function thereby making
>the conversion explicit.

We do want Python to silently convert "cost" to a string in the
proper context.

cost= 3.75
print( cost )

>
>Same with converting objects to bools.

I think "if" is sufficient context to convert something to a boolean.
It now is a matter of good taste and what fits best in Python as a
whole. Nothing to be dogmatic about.

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

[toc] | [prev] | [next] | [standalone]


#25458

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2012-07-17 00:44 -0400
Message-ID<mailman.2199.1342500249.4697.python-list@python.org>
In reply to#25428
On 16 Jul 2012 17:57:45 GMT, Albert van der Horst
<albert@spenarnc.xs4all.nl> declaimed the following in
gmane.comp.python.general:

> In article <b2971c4d-0769-4d03-a7b6-c527629a85c1@x39g2000yqx.googlegroups.com>,
> Ranting Rick  <rantingrickjohnson@gmail.com> wrote:
> 
> >We DON'T want Python to silently convert "cost" to a string. What we
> >DO want is to force the author to use the str function thereby making
> >the conversion explicit.
> 
> We do want Python to silently convert "cost" to a string in the
> proper context.
> 
> cost= 3.75
> print( cost )
>
	Ah, but to some of us, "print" itself implies "convert argument to
human readable string format"... ie, an explicit "cast".
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
        wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#25382

FromDevin Jeanpierre <jeanpierreda@gmail.com>
Date2012-07-15 22:15 -0400
Message-ID<mailman.2159.1342404957.4697.python-list@python.org>
In reply to#25375
On Sun, Jul 15, 2012 at 9:51 PM, Chris Angelico <rosuav@gmail.com> wrote:
>> if bool(obj) and a==b: # Correct!
>> if obj and a==b:       # Incorrect!
>
> That still doesn't answer the question of what bool(obj) should do if
> obj is not a bool, and why if can't do the exact same thing, since if,
> by definition, is looking for a boolean state selector.

If can obviously do the exact same thing -- it does, in Python.

I don't agree with the angle that Rick is spinning, so let me write my
own: By forcing the objects in conditional to be booleans, you are
forced to do something to non-booleans to convert them. By doing so,
you will help inform the reader what the non-boolean is, which makes
it easier for them to figure out the code.

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! :)

As far as I know, the only use of having a polymorphic boolean
conversion is reducing the amount of typing we do. 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.

-- Devin

[toc] | [prev] | [next] | [standalone]


#25386

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 19:58 -0700
Message-ID<50ddab08-0e8d-4f74-8d71-9cc2f538a2f1@m8g2000yqo.googlegroups.com>
In reply to#25382
On Jul 15, 9:15 pm, Devin Jeanpierre <jeanpierr...@gmail.com> 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!?

[toc] | [prev] | [next] | [standalone]


#25391

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-16 04:03 +0000
Message-ID<50039290$0$29978$c3e8da3$5496439d@news.astraweb.com>
In reply to#25382
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 
you made unnecessary assumptions about the implementation.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#25393

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 21:53 -0700
Message-ID<f527e30b-99f1-47e4-9b12-40e3c49f9b8b@o7g2000yqe.googlegroups.com>
In reply to#25391
On Jul 15, 11:03 pm, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> 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()

[toc] | [prev] | [next] | [standalone]


#25395

FromChris Angelico <rosuav@gmail.com>
Date2012-07-16 15:57 +1000
Message-ID<mailman.2162.1342418263.4697.python-list@python.org>
In reply to#25393
On Mon, Jul 16, 2012 at 2:53 PM, Ranting Rick
<rantingrickjohnson@gmail.com> wrote:
> "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.

Proves nothing. At least when there are less names used, there's less
possibility of monkey-patching.

>>> def bool(n):
...     return 5
...
>>> if bool([]):
...     print("Yay?")
...
Yay?

ChrisA

[toc] | [prev] | [next] | [standalone]


#25398

Fromalex23 <wuwei23@gmail.com>
Date2012-07-16 00:21 -0700
Message-ID<45561803-f733-4900-b397-e5e81604a3bb@re8g2000pbc.googlegroups.com>
In reply to#25393
On Jul 16, 2:53 pm, Ranting Rick <rantingrickjohn...@gmail.com> wrote:
> "if obj" is in essence doing "if bool(obj)" behind the scenes. My
> question is: Why hide such valuable information from the reader?

If @decorator is in essence doing "function = decorator(function)"
behind the scenes, why hide that?
If classes are just syntactic sugar for dicts of functions, why hide
that?

> It's
> obvious that "if bool(obj)" will return a boolean; whereas "if obj" is
> ambiguous.

It's only ambiguous if you're the sort of idiot who believes every
language should conform to their a priori expectations. The behaviour
is _documented and standard_, so it's in no way ambiguous unless
someone has actively failed to do _their_ part and _educate
themselves_:

http://docs.python.org/library/stdtypes.html#truth-value-testing

> If the multitudes of misunderstandings from "if obj" on this list have
> not convinced you yet

By that argument, _every_ Python feature that is misunderstood should
be modified to meet the expectations of those who have refused to
understand the language. In which case, why even bother having
different languages with different ways of doing...oh wait, I'm
talking to the monoculture king. Forget that line of reasoning.

Also: citation or STFU. Provide links to 3 threads from the last month
that have revolved around misunderstanding of truth values.

> > > 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!

Yes. That was Steven's point, which you missed in all of your usual
mouth frothing.

[toc] | [prev] | [next] | [standalone]


#25455

FromDevin Jeanpierre <jeanpierreda@gmail.com>
Date2012-07-17 00:18 -0400
Message-ID<mailman.2197.1342498752.4697.python-list@python.org>
In reply to#25391
On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> 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.

If you were confused, instead of assuming I meant something patently
absurd, you should have asked for a clarification.

-- Devin

[toc] | [prev] | [next] | [standalone]


#25463

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-17 06:25 +0000
Message-ID<50050567$0$30002$c3e8da3$5496439d@news.astraweb.com>
In reply to#25455
On Tue, 17 Jul 2012 00:18:28 -0400, Devin Jeanpierre wrote:

> On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano
> <steve+comp.lang.python@pearwood.info> 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

[toc] | [prev] | [next] | [standalone]


Page 1 of 4  [1] 2 3 4  Next page →

Back to top | Article view | comp.lang.python


csiph-web