Check if variable is defined

Andrew Gaul gaul at spam.utexas.edu
Mon May 21 04:04:23 CEST 2001


In article <mailman.990091708.9966.python-list at python.org>, Todd A.
Jacobs wrote:
> On Thu, 17 May 2001, Tim Peters wrote:
>>     if beatsme is None:
>>         print "beatsme wasn't assigned anything meaningful yet"
> 
> This works. It also turns out that:
> 
> 	foo=[]
> 	if foo: print "true"	# print true if foo not empty
> 
> works too, which is the behavior I was looking for. It doesn't work
> quite so well on numbers (your example works better), but is fine for
> lists, which is what I really needed anyway: something to detect empty
> lists.

More generally, many values are considered false: None, 0, and an empty
map or sequence.  From a clarity point of view, 'is None' is often the
best.  It's also the fastest, as the 'is' keyword only checks for object
identity.  I think that None has the same sort of implementation trick
as small integers (it returns the same id()).

One can find more information about truth values here:
http://python.org/doc/current/lib/truth.html .

-- 
     | a | n | d | r | e | w | @ | g | a | u | l | . | o | r | g |
                      White trash.  Loser.  Geek.



More information about the Python-list mailing list