variable update

Steve Holden steve at holdenweb.com
Tue Sep 12 10:24:16 EDT 2006


Fredrik Lundh wrote:
> km wrote:
> 
> 
>>Is there any handy untility for checking if  a variable is populated at 
>>runtime ?
> 
> 
> access it, and catch the NameError:
> 
>     try:
>         variable
>     except NameError:

In a function when accessing a not-yet-bound local variable you may also 
(as Fredrik knows but didn't bother to say) see an UnboundLocalError 
exception,

>         print "not defined"
>     else:
>         print "defined"
> 
> leaving variables undefined is usually bad style, though; if you can, 
> assign some value to it, and test for that value instead:
> 
>     variable = None
> 
>     ... lots of code that may assign to variable ...
> 
>     if variable is not None:
>         print "not defined"
> 
regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list