Python: Assign Value if None Exists Python: Assign Value if None Exists python python

Python: Assign Value if None Exists


You should initialize variables to None and then check it:

var1 = Noneif var1 is None:    var1 = 4

Which can be written in one line as:

var1 = 4 if var1 is None else var1

or using shortcut (but checking against None is recommended)

var1 = var1 or 4

alternatively if you will not have anything assigned to variable that variable name doesn't exist and hence using that later will raise NameError, and you can also use that knowledge to do something like this

try:    var1except NameError:    var1 = 4

but I would advise against that.


var1 = var1 or 4

The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue.


This is a very different style of programming, but I always try to rewrite things that looked like

bar = Noneif foo():    bar = "Baz"if bar is None:    bar = "Quux"

into just:

if foo():    bar = "Baz"else:    bar = "Quux"

That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.