Are nested try/except blocks in python a good programming practice?

后端 未结 11 2082
情歌与酒
情歌与酒 2020-12-07 08:33

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:

dic         


        
11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 09:01

    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.

提交回复
热议问题