假设connectionDetails是一个Python字典,那么像这样重构代码的最佳、最优雅、最“Python”的方式是什么呢?

if "host" in connectionDetails:
    host = connectionDetails["host"]
else:
    host = someDefaultValue

当前回答

你也可以像这样使用defaultdict:

from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"

你可以传递任何普通函数而不是lambda:

from collections import defaultdict
def a():
  return 4

b = defaultdict(a, key="some_value")
b['absent'] => 4
b['key'] => "some_value"

其他回答

您可以使用dict.get()作为默认值。

d = {"a" :1, "b" :2}
x = d.get("a",5)
y = d.get("c",6)

# This will give
# x = 1, y = 6
# as the result

由于"a"在键中,x = d.t get("a",5)将返回相关值1。由于"c"不在键中,y = d.t get("c",6)将返回默认值6。

(这是一个迟来的回答)

另一种方法是继承dict类的子类并实现__missing__()方法,如下所示:

class ConnectionDetails(dict):
    def __missing__(self, key):
        if key == 'host':
            return "localhost"
        raise KeyError(key)

例子:

>>> connection_details = ConnectionDetails(port=80)

>>> connection_details['host']
'localhost'

>>> connection_details['port']
80

>>> connection_details['password']
Traceback (most recent call last):
  File "python", line 1, in <module>
  File "python", line 6, in __missing__
KeyError: 'password'

是这样的:

host = connectionDetails.get('host', someDefaultValue)

我相信所有这些答案都是可以的,但这表明没有“好”的方法来做到这一点。我一直使用字典而不是case语句,并添加一个默认子句,我只是调用以下函数:

def choose(choise, choises, default):
    """Choose a choice from the choises given
    """
    return choises[choise] if choise in choises else default

这样我就可以使用正常的字典,没有特殊的默认子句等。

测试@Tim Pietzcker对Python 3.3.5中PyPy (5.2.0-alpha0)情况的怀疑,我发现.get()和if/else方式确实执行相似。实际上,在if/else情况下,如果条件和赋值涉及相同的键,似乎甚至只有一次查找(与有两次查找的上一种情况相比)。

>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10")
0.011889292989508249
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="try:\n a=d[2]\nexcept KeyError:\n a=10")
0.07310474599944428
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="a=d.get(1, 10)")
0.010391917996457778
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="a=d.get(2, 10)")
0.009348208011942916
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 1 in d:\n a=d[1]\nelse:\n a=10")
0.011475925013655797
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10")
0.009605801998986863
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 2 in d:\n a=d[2]\nelse:\n a=d[1]")
0.017342638995614834