[Python-Dev] bool conversion wart?

Ron Adam rrr at ronadam.com
Fri Feb 23 04:09:05 CET 2007


Larry Hastings wrote:
> Neal Becker wrote:
>> Instead, bool fails in _the worst possible way_: it silently gives a 
>> _wrong result_.
> 
> I disagree with the word "fail" there; Python is working correctly.  The 
> behavior of converting expressions to a boolean is well-defined:
>     http://docs.python.org/ref/Booleans.html
> Perhaps the behavior is unexpected or unwelcome--but it is *correct*.  
> It's just one of those things about Python that one has to get used to; 
> this is a side-effect of another, much more important principle.
> 
> If you really want to turn the string "True" into True, use "eval".
>     eval("4") -> 4
>     eval("True") -> True
>     eval("{}") -> {}
> Perhaps it would be safest to cast the output of eval to bool:
>     bool(eval("True")) -> True
>     bool(eval("")) -> False
> 
> 
> Cheers,
> 
> /larry/

In most cases like this you would not use string "True" or "False" but 
instead values True or False.

In cases where you do have such strings You would probably be doing string 
comparisons anyway because there will most likely be other values to consider.

     if S == "True":  ....

Or use a dictionary to get predetermined values of expected strings.

     if svalues_dict["True"]: ...



To Neal:

Instead of being consistent with numeric types, bool is consistent in a 
different way.  Think of it as len() having precedence over value if that 
helps.

 >>> bool('')
False
 >>> bool([])
False
 >>> bool(())
False
 >>> bool({})
False

 >>> bool('anything')
True
 >>> bool(['anything'])
True
 >>> bool(('anything',))
True
 >>> bool({'any':'thing'})
True

This is really useful because you can do simple if tests to see if 
containers have anything in them.

if somestring: ...

if sometuple: ...

if somelist: ...

if somedict: ...


If they do have contents of some some type, you then need to test the 
contents to see what is in them.  Which might be a True or False values of 
some type.

I suggest you take this to comp.lang.python to get further help with using 
bool.  It is a good idea to test thoughts like this out there first.

Cheers,
   Ron




More information about the Python-Dev mailing list