有没有Python的快捷方式来检查和赋值变量?

7 投票
2 回答
4580 浏览
提问于 2025-04-15 13:17

我发现自己经常在输入以下内容(我在为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)

2 个回答

7

第一个例子说得有点奇怪……为什么要把一个布尔值赋值给另一个布尔值呢?

你可能想表达的是,当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")
25

假设你想在“不存在”的情况下保持myVariable的原值不变,

myVariable = testVariable or myVariable

处理的是第一种情况,而

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

处理的是第二种情况。不过这两者都和“存在”没什么关系(这在Python中几乎不是一个概念;-):第一种是关于真假,第二种是关于在一个集合中是否有某个键。

撰写回答