[Answer]-Python shortcut for test key exists and also assign value to variable

1👍

No, you can’t assign anything in an if test expression.

If you didn’t have the rest of the if block,

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

would work.

It doesn’t make much sense, to do it, though, because id = request.POST.get('id') works just fine with empty request.POST.

Please remember that request.POST can be empty, even if the method was POST. This is what most people would write:

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

0👍

I like this:

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

Leave a comment