question about True values

Tim Chase python.list at tim.thechases.com
Wed Oct 25 15:28:11 EDT 2006


> I'm a little confused. Why doesn't s evaluate to True in the first part, 
>   but it does in the second? Is the first statement something different?
> 
>  >>> s = 'hello'
>  >>> s == True
> False
>  >>> if s:
> 	print 'hi'

The "if s" does an implicit (yeah, I know, "explicit is better 
than implicit") conversion to bool, like

	if bool(s):

And as such, you'll find that

	bool(s) == True

You can learn more at

	http://docs.python.org/lib/truth.html

where you'll see that it's not really exactly a bool() call, but 
that strings are a special case listed here.  And if not, they 
also have a __len__ method which would return zero/non-zero in 
the even that strings weren't handled, making the "actual" test 
(if strings weren't special-cased)

	(s.__len__() <> 0) == True

-tkc







More information about the Python-list mailing list