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

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

当前回答

这并不是我们要问的问题,但是在python字典中有一个方法:dict.setdefault

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

然而,这个方法将connectionDetails['host']的值设置为someDefaultValue,如果key host还没有定义,这与问题不同。

其他回答

虽然.get()是一个很好的习惯用法,但它比if/else慢(并且比try/慢,除非大多数时候字典中会出现键):

>>> 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.07691968797894333
>>> 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.4583777282275605
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="a=d.get(1, 10)")
0.17784020746671558
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="a=d.get(2, 10)")
0.17952161730158878
>>> 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.10071221458065338
>>> 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.06966537335119938

(这是一个迟来的回答)

另一种方法是继承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'

对于多个不同的默认值,请尝试以下方法:

connectionDetails = { "host": "www.example.com" }
defaults = { "host": "127.0.0.1", "port": 8080 }

completeDetails = {}
completeDetails.update(defaults)
completeDetails.update(connectionDetails)
completeDetails["host"]  # ==> "www.example.com"
completeDetails["port"]  # ==> 8080

这并不是我们要问的问题,但是在python字典中有一个方法:dict.setdefault

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

然而,这个方法将connectionDetails['host']的值设置为someDefaultValue,如果key host还没有定义,这与问题不同。

是这样的:

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