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 2 of 4 — ← Prev page 1 [2] 3 4  Next page →


#25477

FromDevin Jeanpierre <jeanpierreda@gmail.com>
Date2012-07-17 05:38 -0400
Message-ID<mailman.2208.1342517936.4697.python-list@python.org>
In reply to#25463
On Tue, Jul 17, 2012 at 2:25 AM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> 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

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


#25387

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-16 02:58 +0000
Message-ID<50038364$0$29995$c3e8da3$5496439d@news.astraweb.com>
In reply to#25375
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_integers_but_might_later_have_more_or_fewer_values_or_other_types = list([1, 2, integer_value_three])

because you can never have too much explicitness. Who wouldn't want
to read code like that?


> 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

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


#25389

FromChris Angelico <rosuav@gmail.com>
Date2012-07-16 13:05 +1000
Message-ID<mailman.2161.1342407951.4697.python-list@python.org>
In reply to#25387
On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> 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*

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


#25390

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 20:21 -0700
Message-ID<a3c97587-9a1f-40e8-9086-d9127f14e17f@b20g2000yqg.googlegroups.com>
In reply to#25387
On Jul 15, 9:58 pm, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> 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>
LogicalFallacyError: "Reductio ad absurdum"

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


#25392

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-16 04:20 +0000
Message-ID<50039698$0$29978$c3e8da3$5496439d@news.astraweb.com>
In reply to#25390
On Sun, 15 Jul 2012 20:21:41 -0700, Ranting Rick wrote:

> On Jul 15, 9:58 pm, Steven D'Aprano <steve
> +comp.lang.pyt...@pearwood.info> 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>
> LogicalFallacyError: "Reductio ad absurdum"


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

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


#25394

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 22:03 -0700
Message-ID<d31ae312-8635-4d61-9c55-f0677e89c196@w6g2000yqg.googlegroups.com>
In reply to#25392
On Jul 15, 11:20 pm, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> 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?

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


#25396

FromChris Angelico <rosuav@gmail.com>
Date2012-07-16 16:00 +1000
Message-ID<mailman.2163.1342418416.4697.python-list@python.org>
In reply to#25394
On Mon, Jul 16, 2012 at 3:03 PM, Ranting Rick
<rantingrickjohnson@gmail.com> wrote:
> 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?

Personally, I'm quite okay with automatic upcasts to string. But if
you want to be explicit, particularly with floats, the solution often
is not to use str(), but a proper number-formatting routine. You want
"String%f"%1.75 for full power.

But when you're just letting the language do the translation, it's
much of a muchness whether you put an explicit toString() call in.

ChrisA

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


#25399

Fromalex23 <wuwei23@gmail.com>
Date2012-07-16 00:27 -0700
Message-ID<d84f508b-7496-49b1-a5c5-5f976156013d@d6g2000pbt.googlegroups.com>
In reply to#25394
On Jul 16, 3:03 pm, Ranting Rick <rantingrickjohn...@gmail.com> wrote:
> 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?

What _other_ than booleans can you expect a condition to reduce down
to? Seriously. What might you possibly expect 'obj' in 'if obj' to be?
Tuesday? The colour mauve? That sinking feeling that you're entering
into a debate that's far above your ability to understand it?

Now: as an expression "String"+1.75 can be _anywhere_, so _what_ you
want will very much be contextual. Do you want "String1.75"? Do you
want float("String") + 1.75? Do you want it to error? So yes, here you
very much need to be explicit.

> Can you reduce this to the absurd?

You've already taken care of that.

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


#25400

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-16 07:52 +0000
Message-ID<5003c824$0$1527$c3e8da3$76491128@news.astraweb.com>
In reply to#25394
On Sun, 15 Jul 2012 22:03:52 -0700, Ranting Rick wrote:

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

The problem with "String" + 1.75 is not lack of explicitness, but 
ambiguity. The + is operator is plenty explicit, but it is ambiguous when 
the operands have different types. Should it...?

- truncate "String" at the first non-digit (hence "") and then coerce
  it to 0.0, and hence return the float 1.75?

- coerce "String" to a float NaN on the basis that "String" is 
  not a number, and hence return NaN?

- coerce 1.75 to a string, and hence return "String1.75"?


The first behaviour is rather dubious, but a good case could be made for 
the second or third. Python takes a fourth approach, and refuses to allow 
such mixed type operations.

If + always meant "numeric addition", and & was used for string 
concatenation, then we could have unambiguous expressions using mixed 
types:

1 + 1.75  # int + float always coerces to float
1 + "2"   # int + str always coerces to int
1 & "2"   # int & str always coerces to str

but since & is used for integer bitwise-and, and + is used for both 
concatenation and addition, we can't, and so Python raises an exception.

For arithmetic, there is an unambiguous hierarchy of types, the numeric 
tower, which tells us which types coerce to what, e.g.:

int -> float -> complex

But there is no such hierarchy when it comes to (say) mixed strings and 
lists, etc., and hence Python raises an exception rather than guessing 
which type you wanted as the result.

This is completely irrelevant when it comes to bools -- we don't have to 
coerce a value into another type, we just need to know if it is something 
or nothing. The object itself is best able to make that decision, hence 
delegating it to a protocol and method:

- If the object is a container, and it has a length of 0, it is empty 
  and hence nothing (falsey); if it has a non-zero length, it is non-empty
  and hence something (truthy).

- Otherwise ask the container whether it is something or nothing by
  calling __nonzero__ (the original name) or __bool__.


Python makes a rather big blunder, at least from the perspective of 
consistency. Bools are ints:

py> issubclass(bool, int)
True
py> isinstance(True, int)
True
py> isinstance(False, int)
True

but there are things that can be converted into bools that can't be 
converted into ints, even though bools *are* ints! Contradiction.

py> x = [None, 42, '']
py> bool(x)
True
py> int(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'list'


Since x can be converted into True, and True == 1, you should be able to 
convert x into 1. But that's crazy, since x = [None, 42, ''].

*shrug* I don't call this a gotcha, but it is one of the more ugly 
consequences of Python's bool implementation.


> Can you
> reduce this to the absurd? Or will you just choose to ignore this valid
> point?

Mu. (Neither true nor false.)



-- 
Steven

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


#25443

FromLaszlo Nagy <gandalf@shopzeus.com>
Date2012-07-16 23:26 +0200
Message-ID<mailman.2191.1342473987.4697.python-list@python.org>
In reply to#25394
> 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?
Not all decisions in Python are based purely on the "explicit enough" 
thing. Some things in the language cannot be explained using 
explicitness alone. So, when we cannot fully explain the ' why 
String+1.75 ' question with statements about explicitness then it 
doesn't mean that anybody lied or wrote something wrong. :-)

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


#25440

FromLaszlo Nagy <gandalf@shopzeus.com>
Date2012-07-16 23:17 +0200
Message-ID<mailman.2190.1342473488.4697.python-list@python.org>
In reply to#25392
>> ...
>>
>> Traceback (most recent quip last):
>>    Author: "<DeAprano>", line 7, in <post>
>> LogicalFallacyError: "Reductio ad absurdum"
>
> 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.

I agree. There is no pont in abolutizing explicitness anyway. It is not 
a yes/no question. You cannot tell that somebody is "not explicit". It 
is not something that can be decided. But you can say that he was "not 
explicit enough" in a concrete case. There is an accepted level of 
explicitness. You can probably always be more expicit, or less explicit. 
Being more explicit is not the goal. But is a good practice to be more 
explicit if it helps you achieve the real goal. For example, writting a 
program that can be maintained easily.

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


#25397

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2012-07-16 07:30 +0100
Message-ID<mailman.2164.1342420227.4697.python-list@python.org>
In reply to#25387
On 16/07/2012 04:05, Chris Angelico wrote:
> On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano
> <steve+comp.lang.python@pearwood.info> 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*
>

What a silly bunt[1] :)
*also ducks for cover*

[1] from a Monty Python sketch for those who don't know about a guy who 
pronounces c's as b's, hence Kings Bollege Bambridge

-- 
Cheers.

Mark Lawrence.


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


#25429

FromAlbert van der Horst <albert@spenarnc.xs4all.nl>
Date2012-07-16 18:03 +0000
Message-ID<m79m6k.9cv@spenarnc.xs4all.nl>
In reply to#25387
In article <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com>,
Steven D'Aprano  <steve+comp.lang.python@pearwood.info> 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:
>
>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_integers_but_might_later_have_more_or_fewer_values_or_other_types = list([1, 2, integer_value_three])
>
>because you can never have too much explicitness. Who wouldn't want
>to read code like that?

Java programmers?

(Couldn't resist ;-) )

>--
>Steven

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]


#25366

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2012-07-15 11:56 -0700
Message-ID<mailman.2150.1342378612.4697.python-list@python.org>
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]


#25414

FromSerhiy Storchaka <storchaka@gmail.com>
Date2012-07-16 16:01 +0300
Message-ID<mailman.2171.1342443677.4697.python-list@python.org>
In reply to#25357
On 15.07.12 19:50, Rick Johnson wrote:
> We must NEVER present "if" in such confusing manner as ExampleA.

## EXAMPLE C ##
py> if bool(money) == True:
...     do_something()

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


#25450

Fromrusi <rustompmody@gmail.com>
Date2012-07-16 18:45 -0700
Message-ID<f2b3fa89-d977-4ffd-8861-6a49fcbaf66c@g4g2000pbn.googlegroups.com>
In reply to#25357
On Jul 15, 9:50 pm, Rick Johnson <rantingrickjohn...@gmail.com> wrote:
> 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.pyt...@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.

If you know some English, its clear that if and while create bool
contexts.
[If you know English but have not studied logic the 'if/while' make
sense whereas 'bool' is gobbledygook]

The issue is not where the cast goes to -- this clearly is bool
But where the cast comes from -- which requires tracing program-paths

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


#25358

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2012-07-15 09:50 -0700
Message-ID<mailman.2143.1342371756.4697.python-list@python.org>
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]


#25381

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-07-16 02:13 +0000
Message-ID<500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com>
In reply to#25354
On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly 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):".

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"). The only "solution" is to throw out 
duck-typing of boolean values, which is tossing the baby out with the 
bathwater -- bool duck-typing works fine for everything else.


> 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__.

Often you should, but I didn't mention anything about testing for None. 
Testing objects in a boolean context is more than just testing for None.

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.

(If seq really could be any type at all, then an explicit identity test 
against None is required.)


One of my favourites:

value = (dict or {}).get('key')

instead of:

value = None if dict is None else dict.get('key')



-- 
Steven

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


#25385

FromRanting Rick <rantingrickjohnson@gmail.com>
Date2012-07-15 19:41 -0700
Message-ID<2e6b36a0-122a-4776-b866-ccd5412bb775@l32g2000yqb.googlegroups.com>
In reply to#25381
On Jul 15, 9:13 pm, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> 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 ([], {}, "")?

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


#25388

FromChris Angelico <rosuav@gmail.com>
Date2012-07-16 12:58 +1000
Message-ID<mailman.2160.1342407523.4697.python-list@python.org>
In reply to#25385
On Mon, Jul 16, 2012 at 12:41 PM, Ranting Rick
<rantingrickjohnson@gmail.com> wrote:
> On Jul 15, 9:13 pm, Steven D'Aprano <steve
> +comp.lang.pyt...@pearwood.info> 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

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


Page 2 of 4 — ← Prev page 1 [2] 3 4  Next page →

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


csiph-web