Implicit conversion to boolean in if and while statements
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Jul 17 03:08:33 EDT 2012
On Tue, 17 Jul 2012 00:19:48 -0500, Andrew Berg wrote:
> To put it in duck-typing terms, why should everything have to quack like
> True or False? Sure, I can see why 1 quacks like True or [] quacks like
> False, but I don't see why say, a Logger or function should quack like
> either.
The default behaviour is that every object is something, hence true-like,
unless explicitly coded to be treated as false-like. Since both loggers
and functions are objects, they are true-like unless the default is
overridden.
If you don't like that simple, consistent model for truthiness, feel free
to design your own language with a different model. Or you can use any
one of the dozens of other existing languages which do what you want.
> Should a Thread object be True if it's been started and False
> otherwise?
If you, the Thread class author, want it to be, you can make it so.
> If it truly is about something vs. nothing, why is a NameError (or
> AttributeError) raised when testing with an undefined variable? Being
> undefined quacks like nothing, doesn't it?
Not really. It doesn't quack like anything.
Are you suggesting that if x doesn't exist, you want this behaviour?
>>> del x # make sure x doesn't exist
>>> if x: print('cheese')
... else:
... print('x is falsy')
... print(x)
...
x is falsy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
OH MAN, that would be SO AWESOME, we should like so do it!!!
(I'm being sarcastic, in case it's not obvious.)
--
Steven
More information about the Python-list
mailing list