【问题标题】:Python shortcut for test key exists and also assign value to variable测试键的 Python 快捷方式存在并且还为变量赋值
【发布时间】:2013-02-18 22:40:20
【问题描述】:

假设我有以下代码:

if request.POST:
   id = request.POST.get('id')
   # block of code to use variable id
   do_work(id)
   do_other_work(id)

是否有一个快捷方式(一行代码)可以测试条件块是否为 request.POST 并为条件块分配变量 id 以使用 id 变量?

我读了这个Is there a Python shortcut for variable checking and assignment?,但并没有真正回答我的问题。

【问题讨论】:

  • 你能写出这段代码的详细版本吗?我对你的措辞有点困惑。
  • @Blender 我想看看我是否可以做类似于 if request.POST and id = request.POST.get('id')

标签: django variables conditional-statements shortcut


【解决方案1】:

不,您不能在 if 测试表达式中分配任何内容。

如果你没有 if 块的其余部分,

id = request.POST and request.POST.get('id')

会起作用的。

不过,这样做没有多大意义,因为 id = request.POST.get('id') 可以很好地处理空的 request.POST

请记住request.POST 可以为空,即使方法是POST。这是大多数人会写的:

if request.method == 'POST':
   id = request.POST.get('id')
   # rest of block

【讨论】:

    【解决方案2】:

    我喜欢这个:

    id = request.POST.get('id', False)
    if id is not False:
        # do something
    

    【讨论】:

      猜你喜欢
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多