Implicit conversion to boolean in if and while statements

Chris Angelico rosuav at
Tue Jul 17 04:13:48 CEST 2012

On Tue, Jul 17, 2012 at 11:57 AM, Andrew Berg <bahamutzero8825 at> wrote:
> I could do:
> if has_message:
>         send('{command} {args} :{message}')
> else:
>         send('{command} {args}')
> but then I'd have to make sure has_message stays accurate since message
> won't necessarily be. Or maybe I could leave message undefined and catch
> the appropriate exception. However, using None is the cleanest and most
> obvious.
> I know Rick likes to troll, but I do agree with him that "if something:"
> for arbitrary objects can be ambiguous or confusing. I don't think
> if/while must have True or False, but not every object has an obvious
> truth value.

Using None when '' is a valid token is the right thing to do (see
also, for instance, SQL's NULL, which is often used the same way). And
then you have gone away from the language's idea of whether a string
is truthy or not, so you get explicit:

if message is not None:
   send('{command} {args} :{message}')

Easy! Or if the language went the other way ("all strings are true"),
it would be the other way around, you'd use "if message!=''" for the
other case. It's not a difficult problem.

Carry on bikeshedding. :)


More information about the Python-list mailing list