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

Paul Prescod paul at prescod.net
Mon Apr 12 00:01:59 EDT 2004


Vineet Jain wrote:

> 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

For most (all?) built-in types there is one and only one false value. If 
you start to accept multiple false values then you run into the types of 
problems Perl programmers run into. You write code like this:

a = input()
if a:
	...
else:
	...

And knowing what it does requires you to keep in mind ALL of the false 
values for the type. So you test your program with one dataset and one 
day another of the false values pops up and your program behaves 
incorrectly. Python's rule is simpler.

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

"false" is just a random English word. The Python builtin is called 
"False".

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

Maybe in your mind. What about "true", "TRUE", "oui", "1.0", "positive" 
and "yeah". How far do you intend to go? Name a single language or 
system that treats "True", "on", "1" and "yes" as positive values and 
"False", "off", "0" and "no" as negative values. If Python started 
guessing what strings are vaguely affirmative, people would always 
"expect" it to read their minds just a little bit more effectively than 
it does. The current rule is very simple: the empty string is false. All 
others are true. It is trivially easy for you to redefine conversion to 
boolean for any particular data set:

def mybool():
	return mystring=="oui"

  Paul Prescod






More information about the Python-list mailing list