Does a function like isset() exist in Python?

Roy Smith roy at panix.com
Thu Jun 23 08:35:42 EDT 2005


In article <mailman.784.1119496200.10512.python-list at python.org>,
 Patrick Fitzsimmons <patfitz at gmail.com> wrote:

> Hi,
> 
> I'm sure I should know this, but I can't find it in the manual.
> 
> Is there a function in Python like the function in PHP isset()?  It
> should take a variable name and return True or False depending on
> whether the variable is initialized.
> 
> Thanks for any help,
> Patrick

The straight-forward thing would be to simply access the variable and catch 
any resulting NameError exception that's raised if it's not defined:

try:
   x
   print "x is defined"
except NameError:
   print "no it's not"

Next question, why do you want to do this?  I suspect for most idioms where 
you would something like this, the more pythonic way would be to set the 
variable to None at some point, then test to see if it's still None later 
on:

x = None
while foo:
   if blah:
      x = baz

if x != None:
   print "x was assigned a value"



More information about the Python-list mailing list