Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True

Vineet Jain vineet at eswap.com
Sun Apr 11 23:00:28 EDT 2004


Thanks for the code suggestion.

>From what I've read, most people (including me) are attracted to Python
because of how natural it is. Give that is a high priority for the language
designers:

How can anyone argue that

bool('false') = True

is more natural (and what you would expect) than

bool('false') = False

Having just got over the surprise that int('2.1') fails while
int(float('2.1')) works the above surprises me even more. If the int case
was rejected because it is 'better to be explicit than not' then how can you
bool('false') be allowed??

I still think int('2.1') should return 2. If the programmer is using int
then he should know that what he will get out of the result is an int
regardless of what comes in. Especially since int accepts a float object in
any case. It seems a waste of resources to have to first convert a string to
a float object and then convert it to an int object.

Booleans are associated with (True, on, 1 and yes) and bool() on any them
should return True.

VJ

-----Original Message-----
From: Jeff Epler [mailto:jepler at unpythonic.net]
Sent: Sunday, April 11, 2004 5:35 PM
To: Vineet Jain
Cc: python-list at python.org
Subject: Re: Is there a boolean(somestring) equivalent of
int(somestring). bool('false') -> True


The reason that
>>> bool('false')
returns True is the same reason that
>>> not 'false'
is False:  A non-empty string, when treated as a boolean, is true.

Changing the meaning of bool() is not likely to happen.

Here's one piece of code you might try to get the behavior you desire:

true_values = '1 yes true on'.split()
false_values = '0 no false off'.split()
def parse_boolean_value(s):
    if s in true_values: return True
    if s in false_values: return False
    raise ValueError

'i in seq' is just like checking whether any item in seq is equal to i.
If seq is a dictionary or a set (or defines __contains__), this test can
be a little more efficient, but the efficiency is unlikely to matter
when there are only 4 items.

Jeff





More information about the Python-list mailing list