Variables and none?

Terry Reedy tjreedy at udel.edu
Sat Jan 21 18:23:02 EST 2006


"Steve Holden" <steve at holdenweb.com> wrote in message 
news:dqsbbe$db6$1 at sea.gmane.org...
> 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






More information about the Python-list mailing list