how to conditionally add a dict in-line

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Feb 24 00:33:37 EST 2009


On Mon, 23 Feb 2009 21:56:46 -0700, Wes James wrote:

>> vars = {'_page': i}
>> if request.vars._query is not None:
>>    vars['_query'] = request.vars._query
> 
> Could this be:
> 
> vars = {'_page': i}
>  if request.vars._query:
>     vars['_query'] = request.vars._query


Instead of typing "request.vars._query" in all the examples, I'm going to 
abbreviate it as "x" instead.

"if x is not None" and "if x" are very different things. Consider the 
following examples:


>>> x = None
>>>
>>> if x is not None:
...     print "action performed when x is not None"
... else:
...     print "do nothing"
...
do nothing
>>>
>>> if x:
...     print "action performed when x is not None"
... else:
...     print "do nothing"
...
do nothing


So far so good. Both pieces of code do the right thing when x actually is 
None. But what happens if x is *not* None?


>>> x = ""  # The empty string is *not* None.
>>>
>>> if x is not None:
...     print "action performed when x is not None"
... else:
...     print "do nothing"
...
action performed when x is not None
>>>
>>> if x:
...     print "action performed when x is not None"
... else:
...     print "do nothing"
...
do nothing



That's clearly wrong, because we know that x isn't None, it is the empty 
string. The test "if x" does not test for the same thing as "if x is not 
None". "if x" tests the general truth value of any object, and many 
objects have a false truth value: None, empty string, 0, [], {} and many 
more.




-- 
Steven



More information about the Python-list mailing list