Implicit conversion to boolean in if and while statements

Andrew Berg bahamutzero8825 at gmail.com
Tue Jul 17 03:22:18 CEST 2012


On 7/15/2012 3:28 PM, Terry Reedy wrote:
> Because everything does (or should).
I can see how truth testing for empty values is convenient, but perhaps
objects should only have a truth value if explicitly given one -
particularly in cases where such a value wouldn't be obvious or the
obvious value isn't the actual one:

>>> c = types.SimpleNamespace()
>>> if c: print('c')
...
c
>>> c.__dict__
{}

Would it not be reasonable to expect an empty namespace to have a truth
value of False since [] and friends do? It's a bit of a gray area for an
object defined by "class C: pass", but this is *specifically intended*
to be a namespace. Why should things like functions or exceptions have
truth values?

Note: For those who aren't aware, types.SimpleNamespace was added in
3.3.0b1.

On a side note, I tend to do this:

x = some_list
try:
	y = x.pop()
except IndexError:
	do_something_else()

rather than:

if x:
	y = x.pop()
else:
	do_something_else()

but of course that only applies to empty lists/sets/related and not
0/0.0/None and only when I want something from the list/set/whatever.
-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803



More information about the Python-list mailing list