`if key in dict` vs. `try/except` - which is more readable idiom?

前端 未结 10 2511
陌清茗
陌清茗 2020-11-28 06:19

I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case:

I want to build dictionary A from dict

10条回答
  •  感动是毒
    2020-11-28 06:42

    Though the accepted answer's emphasize on "look before you leap" principle might apply to most languages, more pythonic might be the first approach, based on the python principles. Not to mention it is a legitimate coding style in python. Important thing is to make sure you are using the try except block in the right context and is following best practices. Eg. doing too many things in a try block, catching a very broad exception, or worse- the bare except clause etc.

    Easier to ask for forgiveness than permission. (EAFP)

    See the python docs reference here.

    Also, this blog from Brett, one of the core devs, touches most of this in brief.

    See another SO discussion here:

提交回复
热议问题