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 docs recommend this style known as EAFP.

Personally, I prefer to avoid nesting when it's not necessary:

    def __getattribute__(self, item):
        try:
            return object.__getattribute__(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.

From: stackoverflow.com/q/17015230

Back to homepage or read more recommendations: