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

 
 
Chris Angelico
Guest
Posts: n/a
 
      07-16-2012
On Mon, Jul 16, 2012 at 2:53 PM, Ranting Rick
<> 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
 
Reply With Quote
 
 
 
 
Chris Angelico
Guest
Posts: n/a
 
      07-16-2012
On Mon, Jul 16, 2012 at 3:03 PM, 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? 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
 
Reply With Quote
 
 
 
 
Mark Lawrence
Guest
Posts: n/a
 
      07-16-2012
On 16/07/2012 04:05, Chris Angelico wrote:
> On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano
> <steve+> 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.



 
Reply With Quote
 
alex23
Guest
Posts: n/a
 
      07-16-2012
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/stdty...-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.
 
Reply With Quote
 
alex23
Guest
Posts: n/a
 
      07-16-2012
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.
 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      07-16-2012
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
 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      07-16-2012
On Sun, 15 Jul 2012 19:41:34 -0700, Ranting Rick wrote:

> 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 ([], {}, "")?



Mostly for explicitness. I want to be able to say that there is
*explicitly* no seq, not merely that it happens to be a list which right
now is empty but later might not be. Using None for missing values is
idiomatic Python.

You should approve, if only for the sake of consistency: None is meant to
be used as "no such value", and that's exactly how I am using it, even at
the cost of my convenience when writing the code.


--
Steven
 
Reply With Quote
 
Serhiy Storchaka
Guest
Posts: n/a
 
      07-16-2012
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()

 
Reply With Quote
 
Dennis Lee Bieber
Guest
Posts: n/a
 
      07-16-2012
On 16 Jul 2012 02:38:35 GMT, Steven D'Aprano
<steve+> declaimed the following in
gmane.comp.python.general:

> On Sun, 15 Jul 2012 12:02:37 -0500, Andrew Berg wrote:
>


> > Okay, I see the value in this, but I don't understand why None has a
> > truth value.

>
> And this is exactly the sort of mental confusion that Laura Crichton
> warned about (see the link I included earlier).
>


Would one rather have the behavior seen in SQL for Null?
http://www.firebirdsql.org/file/docu...Null-Guide.pdf

Hey, let's turn the IF statement into tri-state logic...

if cond:
#true branch
else:
#false branch
unknown:
#when cond includes a None term that was NOT explicitly
#part of a "... is {not} None" clause
--
Wulfraed Dennis Lee Bieber AF6VN
HTTP://wlfraed.home.netcom.com/

 
Reply With Quote
 
Albert van der Horst
Guest
Posts: n/a
 
      07-16-2012
In article <b2971c4d-0769-4d03-a7b6->,
Ranting Rick <> 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

 
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
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57