Get rid of recursive call __getattr__

bruno at modulix onurb at xiludom.gro
Thu Dec 15 04:55:28 EST 2005


Steve Holden wrote:
> Peter Otten wrote:
> 
>> Pelmen wrote:
>>
>>
>>>>>> class Test:
>>>
>>>
>>>          def __getattr__(self, attr):
>>>            print attr
>>>
>>>          def foo(x):
>>>            print x
>>>
>>>
>>>>>> t = Test()
>>>>>> print t
>>>
>>>
>>> __str__
>>>
>>> Traceback (most recent call last):
>>>  File "<pyshell#23>", line 1, in -toplevel-
>>>    print t
>>> TypeError: 'NoneType' object is not callable
>>>
>>> what i have to do? define __str__ explicitly?
>>
>>
>>
>> By seemingly not returning anything your __getattr__() method actually
>> returns None. Instead you should raise an AttributeError when your
>> __getattr__() encounters the name of an attribute it doesn't handle.
>> Let's assume Test.__getattr__() should implement an attribute 'alpha' and
>> nothing else:
>>
>>
>>>>> class Test:
>>
>>
>> ...     def __getattr__(self, name):
>> ...             print "looking up", name
>> ...             if name == "alpha":
>> ...                     return 42
>> ...             print "lookup failed for", name
>> ...             raise AttributeError
> 
> 
> or, rather better IMHO,
> 
>                   raise AttributeError("lookup failed for %s" % name)

or still better in IMNSHO:
  raise AttributeError("%s object has no attribute %s" %
                       \ (self.__class__.__name__,
                          name))

(which is the 'standard' AttributeError message)



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list