假设connectionDetails是一个Python字典,那么像这样重构代码的最佳、最优雅、最“Python”的方式是什么呢?
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
假设connectionDetails是一个Python字典,那么像这样重构代码的最佳、最优雅、最“Python”的方式是什么呢?
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
当前回答
(这是一个迟来的回答)
另一种方法是继承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)
(这是一个迟来的回答)
另一种方法是继承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'
您可以使用一个lamba函数作为一行程序。创建一个新对象connectionDetails2,可以像函数一样访问它…
connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT"
现在使用
connectionDetails2(k)
而不是
connectionDetails[k]
如果k在键中,则返回字典值,否则返回"DEFAULT"
我相信所有这些答案都是可以的,但这表明没有“好”的方法来做到这一点。我一直使用字典而不是case语句,并添加一个默认子句,我只是调用以下函数:
def choose(choise, choises, default):
"""Choose a choice from the choises given
"""
return choises[choise] if choise in choises else default
这样我就可以使用正常的字典,没有特殊的默认子句等。
对于多个不同的默认值,请尝试以下方法:
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