Is there a Python shortcut for variable checking and assignment?

django, idioms, python

Solution

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.

Problem

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)`?

Original source