"Steve Holden" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Ivan Shevanski wrote:
>> python way to detect if a variable exsists? Say I had a program that
>> needed a certain variable to be set to run and the variable was not
>> found when it came time to use it. . .Would I just have to catch the
>> error, or could I have python look for the variable beforehand?
>>
> The usual way to do this is to catch the error.
>
> If you can access the namespace of interest (say it's an instance of
> some class) then you can use hasattr() to answer the question, but
> catching the exception is the generic way to do it.
According to what I recently read, hasattr is purely syntactic sugar. It
answers that question by invoking gettattr in the C equivalent of a try
clause.
def hasattr(ob, name): # this and below untested
try:
getattr(ob,name)
return True
except AttributeError:
return False
So if the attribute exists, it is retrieved twice -- the first time to tell
the caller that it is okay to get it again the second time.
Perhaps we should have hasgetattr(ob, name):
def hasgetattr(ob, name):
try:
return True, getattr(ob, name)
except AttributeError:
return False, None
This could be used like so:
has,val = hasgetattr(ob, attr)
if has: <code using val>
Terry J. Reedy
--
http://mail.python.org/mailman/listinfo/python-list