["python"]
Are nested try/except blocks in Python a good programming practice?

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?
Your first example is perfectly fine. Even the official Python documentation recommends this style known as EAFP. Personally, I prefer to avoid nesting when it's not necessary: def __getattribute__(self, item): try: return object.__getattribute__(self, item) except AttributeError: pass # Fallback to dict try: return self.dict[item] except KeyError: raise AttributeError("The object doesn't have such attribute") from None PS. has_key() has been deprecated for a long time in Python 2. Use item in self.dict instead.