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

发布于 2024-07-29 03:14:06 字数 436 浏览 5 评论 0原文

我发现自己经常输入以下内容(为 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 = allocate_if_exists(testVariable) 的东西?

I'm finding myself typing the following a lot (developing for Django, if that's relevant):

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

Alternatively, and more commonly (i.e. building up a parameters list)

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

Is there a shortcut I just don't know about that simplifies this? Something with the kind of logic myVariable = assign_if_exists(testVariable)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清晰传感 2024-08-05 03:14:06

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

myVariable = testVariable or myVariable

处理第一种情况,然后

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

处理第二种情况。 不过,两者都与“存在”没有太大关系(这几乎不是 Python 概念;-):第一个是关于 true 或 false,第二个是关于集合中键的存在或不存在。

Assuming you want to leave myVariable untouched to its previous value in the "not exist" case,

myVariable = testVariable or myVariable

deals with the first case, and

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

deals with the second one. Neither has much to do with "exist", though (which is hardly a Python concept;-): the first one is about true or false, the second one about presence or absence of a key in a collection.

苯莒 2024-08-05 03:14:06

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

您可能的意思是,当 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")

The first instance is stated oddly... Why set a boolean to another boolean?

What you may mean is to set myVariable to testVariable when testVariable is not a zero length string or not None or not something that happens to evaluate to False.

If so, I prefer the more explicit formulations

myVariable = testVariable if bool(testVariable) else somethingElse

myVariable = testVariable if testVariable is not None else somethingElse

When indexing into a dictionary, simply use get.

myVariable = request.POST.get('query',"No Query")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文