`if key in dict`与`try / except`-哪个更易读? [英] `if key in dict` vs. `try/except` - which is more readable idiom?

查看:118
本文介绍了`if key in dict`与`try / except`-哪个更易读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于成语和可读性的问题,在这种情况下似乎存在Python哲学冲突:

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

我想从字典构建字典A B.如果B中不存在特定的键,则什么也不做,然后继续。

I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on.

哪种方法更好?

try:
    A["blah"] = B["blah"]
except KeyError:
    pass

if "blah" in B:
    A["blah"] = B["blah"]

请宽恕还是简单明了。

哪个更好,为什么?

推荐答案

异常不是有条件的。

有条件的版本更加清晰。这很自然:这是简单明了的流控制,这是为条件而设计的,不是针对异常的。

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

异常版本主要用于在环境中执行这些查找时的优化。循环:对于某些算法,它允许从内部循环中消除测试。这里没有那种好处。它具有一个小优点,它避免了不得不说两次等等 ,但是,如果您要进行很多这样的操作,您可能应该有一个帮助者 move_key 函数。

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.

这篇关于`if key in dict`与`try / except`-哪个更易读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆