__getattr__, hasattr

Steve Tregidgo stregidgo at quantisci.co.uk
Tue Dec 14 08:28:47 EST 1999


Hi Ionel,

For hasattr to return 0, __getattr__ must raise an AttributeError:

class does_not_work:
  def __getattr__(self, name):
    if name in ['spam', 'eggs', 'chips']:
      return 1
    return 0

class works:
  def __getattr__(self, name):
    if name not in ['spam', 'eggs', 'chips']:
      raise AttributeError, name

>>> x = does_not_work()
>>> y = works()
>>> hasattr(x, 'spam') # Seems okay...
1
>>> hasattr(x, 'a')    # Whoops!  It's broken.
1
>>> hasattr(y, 'spam') # As expected
1
>>> hasattr(y, 'a')    # Hurrah!  False!
0
>>>

It is possible for __getattr__ to return any value at all, so testing
its output won't work -- if x.spam is actually None, which evaluates as
false, you'd be told that spam was not an attribute of x!

Hope this helps,
Steve Tregidgo
http://www.enviros.com/bc


Ionel Simionescu wrote:
> 
> Hi,
> 
> It seems that since one defines __getattr__,
> hasattr(obj, name) will happily answer 'yes' irrespective of the attribute
> name.
> 
> This does not appear very sound to me.
> Do I overlook anything?
> 
> Thanks,
> ionel



More information about the Python-list mailing list