【问题标题】:Is there a Python shortcut for variable checking and assignment?是否有用于变量检查和赋值的 Python 快捷方式?
【发布时间】:2010-11-15 11:50:06
【问题描述】:

我发现自己经常输入以下内容(为 Django 开发,如果相关的话):

if testVariable then:
   myVariable = testVariable
else:
   # something else

另外,更常见的是(即建立一个参数列表)

if 'query' in request.POST.keys() then:
   myVariable = request.POST['query']
else:
   # something else, probably looking at other keys

有没有我不知道的捷径可以简化这个过程?有点逻辑myVariable = assign_if_exists(testVariable)

【问题讨论】:

    标签: python django idioms


    【解决方案1】:

    假设您想让 myVariable 在“不存在”的情况下保持其先前的值不变,

    myVariable = testVariable or myVariable
    

    处理第一种情况,并且

    myVariable = request.POST.get('query', myVariable)
    

    处理第二个。不过,两者都与“存在”无关(这几乎不是 Python 的概念;-):第一个是关于真或假,第二个是关于集合中是否存在键。

    【讨论】:

    • 第一个成语真的很好:前几天才知道。
    • 谢谢,完美。想知道到目前为止我是如何错过这个语法糖的!
    【解决方案2】:

    第一个实例的陈述很奇怪......为什么将一个布尔值设置为另一个布尔值?

    您可能的意思是当 testVariable 不是零长度字符串或不是 None 或不是碰巧评估为 False 的东西时,将 myVariable 设置为 testVariable。

    如果是这样,我更喜欢更明确的表述

    myVariable = testVariable if bool(testVariable) else somethingElse
    
    myVariable = testVariable if testVariable is not None else somethingElse
    

    索引到字典时,只需使用get

    myVariable = request.POST.get('query',"No Query")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      相关资源
      最近更新 更多