How can I tell if variable is defined

Rami Chowdhury rami.chowdhury at gmail.com
Tue Sep 22 20:35:44 CEST 2009


On Tue, 22 Sep 2009 11:03:25 -0700, Brown, Rodrick   
<rodrick.brown at citi.com> wrote:

> How could I do the following check in Python
>
> In Perl I could do something like if ((defined($a)) { ... }
>
> I tried if var is not None:
> However this doesn't seem to work as described.
>
> Thanks.

Could you let us know in what context you're checking to see if a variable  
is defined? If you mean "has the name been used before", then bear in mind  
Python is a lot stricter about this kind of thing than Perl, and if you've  
never used 'var' before the if-statement, you'll probably get a NameError  
being raised.

If you want to check whether the name 'var' is bound to a meaningful  
object, however (e.g. if it's an optional argument to a function, and you  
know it exists, but don't know if it's bound to meaningful data) then your  
construction should work.


-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)



More information about the Python-list mailing list