[Tutor] Test if name is defined?

Jeff Shannon jeff@ccvcorp.com
Tue Feb 11 12:55:46 2003


Terry Carroll wrote:

>Is there a way to test to see if a variable is defined other than with the 
>exception system?
>
>[...]
>
>I only want to keep the object if I read in a value for either the 
>attribute kGB0 or kBigFive attributes (or both) are defined.
>

Well, for one, trying and catching exceptions is a recognized valid 
method of introspection in Python.  The fact that you are using 
try/except to determine whether something is defined, is *not* a sign of 
bad design.  (Python considers the use of exceptions to be much more 
normal than some other languages, and it is not reserved only for true 
error conditions.)

Secondly, if what you're trying to determine is whether an *object* has 
a certain *attribute* defined, then you can use the built-in function 
hasattr().  Alternatively, if you're working with dictionaries, there's 
a has_key() method that will tell you whether a certain key already 
exists in the dictionary.

 >>> class X:
...     def __init__(self):
...         self.eggs = 1
...        
 >>> x = X()
 >>> hasattr(x, "eggs")
1
 >>> hasattr(x, "spam")
0
 >>> d = { "spam":1 }
 >>> d.has_key("spam")
1
 >>> d.has_key("eggs")
0
 >>>

Jeff Shannon
Technician/Programmer
Credit International