Checking for an "undefined" variable - newbie question

Alex Martelli aleax at
Wed Aug 6 13:37:27 CEST 2003

Dan Rawson wrote:

> How do I check if a variable has been defined??
> The following don't appear to work:
> if variable:
> if variable is None:
> I have only one (ugly) solution:
> try:
>      variable
> except NameError:
>      ...

This is the canonical solution.  Personally, I find it quite nice
that an ugly architecture (such as one based on whether a variable
is already defined/initialized rather than initializing it at the
start with a unique value and testing for that!) requires an ugly
way of expressing it.  Unfortunately there are nicer ones such as
"if 'variable' not in locals() and 'variable' not in globals():" but
at least they're verbose and slow:-).

If you can't rule out (e.g.) None as a valid value for your
variable, just make a unique placeholder value such as [be
sure to use a MUTABLE value, else uniqueness is not guaranteed]:

class _uninitialized: pass

initialize your variable at the start of your scope with

variable = _uninitialized

and test at any point within that scope whether the variable
is still uninitialized or has been assigned an actual value by

if variable is _uninitialized:

It seems to me that this is far preferable to any approach
based on _not_ binding the name 'variable' at all and later
needing to test whether the name is bound or not.


More information about the Python-list mailing list