views:

545

answers:

2

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

+6  A: 

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")
S.Lott
+16  A: 

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.

Alex Martelli
The first idiom is really nice: only found out about this the other day.
jkp
Thanks, perfect. Wonder how I managed to miss this syntactic sugar so far!