【问题标题】:What is the scenario of dict.get('..', None) or None?dict.get('..', None) 或 None 的场景是什么?
【发布时间】:2018-03-14 18:50:55
【问题描述】:

如果在某个开源库中发现以下代码:

message.get('title', None) or None

有什么理由这样做而不是message.get('title', None)

【问题讨论】:

  • .get(..., None) 中的None 实在是多余和多余。

标签: python python-3.x


【解决方案1】:

这将保证字典中的任何虚假值(例如None''0False[]、...)都会变成None。即如果你有

d = {'title': False}

然后

d.get('title', None)  # False
d.get('title', None) or None  # None

这是否有一个实用的用例值得商榷,但肯定存在细微差别......


还请注意,您可以将其简化为:

d.get('title') or None

因为d.get 默认在没有找到元素时返回None

【讨论】:

  • fwiw,一个实际的用例是os.environ.get('VAR') or 'some_default' 这样$ VAR= python ... 将等同于未设置。
【解决方案2】:

是有原因的。

例如,message.get('title', None) or None 可以返回一个空字符串。 Python中空字符串的布尔值是False,所以会返回None

这也适用于从 dict 返回且计算结果为 False 的任何其他值。 None 将被返回。

注意:但是,该代码最好写成message.get('title') or None,因为无论如何dict.get默认返回None(第二个参数)。

【讨论】:

  • 不,它不会返回空字符串。
【解决方案3】:

如果您收到消息并且它是一个 false-y 值,这会将其更改为无。

例如

message = {'title' : ''}

message.get('title', None)
>> ''

message.get('title', None) or None 
>> None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2020-11-19
    • 2014-02-23
    • 2018-01-04
    • 1970-01-01
    相关资源
    最近更新 更多