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

前端 未结 10 2486
陌清茗
陌清茗 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:40

    Exceptions are not conditionals.

    The conditional version is clearer. That's natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions.

    The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminating tests from inner loops. It doesn't have that benefit here. It has the small advantage that it avoids having to say "blah" twice, but if you're doing a lot of these you should probably have a helper move_key function anyway.

    In general, I'd strongly recommend sticking with the conditional version by default unless you have a specific reason not to. Conditionals are the obvious way to do this, which is usually a strong recommendation to prefer one solution over another.

提交回复
热议问题