I'm writing my own container, which needs to give access to a dictionary inside by attribute calls. The typical use of the container would be like this:
dict_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
I know that it might be stupid to write something like this, but that's the functionality I need to provide. I was thinking about implementing this in a following way:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
try:
return self.dict[item]
except KeyError:
print "The object doesn't have such attribute"
I'm not sure whether nested try/except blocks are a good practice, so another way would be to use hasattr()
and has_key()
:
def __getattribute__(self, item):
if hasattr(self, item):
return object.__getattribute__(item)
else:
if self.dict.has_key(item):
return self.dict[item]
else:
raise AttributeError("some customised error")
Or to use one of them and one try catch block like this:
def __getattribute__(self, item):
if hasattr(self, item):
return object.__getattribute__(item)
else:
try:
return self.dict[item]
except KeyError:
raise AttributeError("some customised error")
Which option is most Pythonic and elegant?