Implicit conversion to boolean in if and while statements
steve+comp.lang.python at pearwood.info
Tue Jul 17 06:11:04 CEST 2012
On Mon, 16 Jul 2012 20:22:18 -0500, Andrew Berg wrote:
> 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:
You have run into Python's default behaviour: objects are treated as
something by default. If you want them to represent nothing, you have to
explicitly code that case.
py> o = object()
Yet again, thinking about something versus nothing instead of true/false
makes the behaviour both obvious and correct: of course an object should
be treated as something (true-like) rather than nothing (false-like) by
default, it's an *object* is it not?
If you want your type to implement non-default semantics, such as
container semantics, then you need to code it.
>>>> c = types.SimpleNamespace()
>>>> if c: print('c')
> 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?
And this is a good life-lesson that any class called "SimpleFoo" will not
stay simple for long.
If you are right that SimpleNamespace should be treated as a container,
then it should implement container semantics. Since it doesn't, that is
1) a bug; or
2) a triumph of laziness over correctness
I imagine though that the Python dev's answer will basically be #2: "it
isn't a container, it just behaves a little bit like a container, except
when it doesn't" kinda thing. But feel free to report it as a bug and see
(This is not *entirely* wrong, because SimpleNamespace certainly doesn't
*claim* to be a container, nor does it expose the full container API. But
it should, even if that means it is no longer quite so simple.)
More information about the Python-list