__getattr__ question

Laszlo Nagy gandalf at designaproduct.biz
Fri Jun 9 13:21:12 EDT 2006


  Hello,

This is from the Python documentation (fragment):

__getattr__(     self, name)
    Called when an attribute lookup has not found the attribute in the 
usual places (i.e. it is not an instance attribute nor is it found in 
the class tree for self). name is the attribute name. This method should 
return the (computed) attribute value or raise an AttributeError exception.


How can I determine if an attribute can be found in the usual places? 
Here is an example program that will enlight the basic problem.

class TemplateItem(object):
    def __init__(self,name):     
        self.name = name
        self.items = [] # Order of items is important
    def __getattr__(self,name):
        """I would like to access the items easily, with their name (if 
possible)"""
        for item in self.items:
                if hasattr(item,'name') and item.name == name:
                    return item
        raise AttributeError("%s: attribute or item does not exists."%name)
    def __str__(self):
        return "TemplateItem('%s')"%self.name
   
class CustomTemplateItem(TemplateItem):
    pass # I could have been customized this...
   

root = CustomTemplateItem('root')
i1 = CustomTemplateItem('item1')
i2 = CustomTemplateItem('item2')

root.items.append(i1)
root.items.append(i2)
TemplateItem.item3 = TemplateItem('item3')

print root
print root.item1
print root.item2
print root.item3

Of course this program will print:

TemplateItem('root')
TemplateItem('item1')
TemplateItem('item2')
TemplateItem('item3')

So how can I tell if 'root.item3' COULD BE FOUND IN THE USUAL PLACES, or 
if it is something that was calculated by __getattr__ ?
Of course technically, this is possible and I could give a horrible 
method that tells this...
But is there an easy, reliable and thread safe way in the Python 
language to give the answer?

Thanks,

    Laszlo




More information about the Python-list mailing list