Search code examples
python-2.7keyerror

Attribute Dict -- TypeError raised when getting documentation


I wrote an "AttributeDict"-like object from the Alchin 'pro python' book, (below is taken almost directly from the book. My goal is to create a config object where the config fields are accessible as class attributes).

class ADict(dict):
    def __setattr__(self,key,value):
        self[key] = value
    def __getattr__(self,key):
        return self[key]

When I try to access the documentation I get a TypeError, related to a missing __name__ attribute (example below).

>>> z = ADict()
>>> help(z)
line 1531, in doc
pager(render_doc(thing, title, forceload))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.py",   line 1505, in render_doc
object, name = resolve(thing, forceload)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.py", line 1500, in resolve
name = getattr(thing, '__name__', None)
File "attributeConfig.py", line 26, in __getattr__
return self[key]
KeyError: '__name__'

What's going on here? It's not obvious to me where this __name__ is going to (and how it's being used in the pydoc code).


Solution

  • You need to make sure an AttributeError is raised when the attribute couldn't be found:

    class ADict(dict):
    
        def __setattr__(self,key,value):
            self[key] = value
    
        def __getattr__(self,key):
            try:
                return self[key]
            except KeyError:
                raise AttributeError
    

    This will lookup the attribute in the dictionary first. If it's there, return it. Otherwise, use raise an AttributeError to indicate that the attribute isn't there.