[Tutor] Test if name is defined?

Terry Carroll carroll@tjc.com
Tue Feb 11 13:13:26 2003


On Tue, 11 Feb 2003, Jeff Shannon wrote:

> 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.  

Thanks; I understand that, it just gets unweidly when you're trying to 
test multiple variables, and want to proceed if any one variable is 
defined.

> 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().  

Excellent!

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

And, most importantly for me, I can still do:

>>> hasattr(x,"spam")
0
>>> x.spam = 1
>>> hasattr(x,"spam")
1

This would do what I want.  Thanks.

I've already changed my approach to add a "valid" flag to the object; it's 
__init__ially set to 0, but I set it to 1 when I add either the kGB0 or 
kBigFive; then my test is simply against the flag, rather than for those 
attribute's definitions.

This will work for me because I have a simple "or" condition, but I'll 
definitely keep hasattr() in mind for the future.  Thanks.


-- 
Terry Carroll        |  "To have this rare opportunity
Santa Clara, CA      |    is a rare opportunity."
carroll@tjc.com      |    - Houston Rockets' Yao Ming, on being named
Modell delendus est  |    starting center for the 2003 NBA All-Star Game