Is there a Python shortcut for variable checking and assignment?

霸气de小男生 提交于 2020-01-03 09:04:24

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/1207333/is-there-a-python-shortcut-for-variable-checking-and-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!