Implicit conversion to boolean in if and while statements

Andrew Berg bahamutzero8825 at gmail.com
Tue Jul 17 03:57:43 CEST 2012


On 7/16/2012 7:43 PM, Steven D'Aprano wrote:
> The existence of a jar or no jar is irrelevant to the question of how 
> many jellybeans there are. They are two different things, and therefore 
> need two different values. There are many ways to implement this.
I have a better real example, but I opted not to use it before since it
requires some explanation - IRC messages.
A client-to-server message has the basic form of b'COMMAND arguments
:message' (e.g. b'PRIVMSG #channel :hi guys!'). Some commands have no
message part because there is no message associated with it (e.g. b'JOIN
#channel') and there is at least one where there is a big difference
between a blank message (b'') and no message - b'TOPIC #channel' is a
request for the topic while b'TOPIC #channel :' clears the topic since
the part after the b':' is b'' (b'TOPIC #channel :Welcome to #channel'
sets the topic to "Welcome to #channel"). In my code, I would have an
object representing a message rather than parsing it multiple times. If
the message
attribute is not None, I send b'{command} {args} :{message}', otherwise
b'{command} {args}'. If I considered '' falsey, either I would require
all messages to have ":" (which would not actually be part of the
message) or have any request to view the topic as a channel op clear the
topic. This would apply to the server parsing the message as well. A few
other commands have messages optional as well, but they are not as
serious as TOPIC.

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.
-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803



More information about the Python-list mailing list