Python: Assign Value if None Exists

Spencer picture Spencer · Sep 7, 2011 · Viewed 167.8k times · Source

I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want:

# only if var1 has not been previously assigned

var1 = 4

Answer

Anurag Uniyal picture Anurag Uniyal · Sep 7, 2011

You should initialize variables to None and then check it:

var1 = None
if 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:
    var1
except NameError:
    var1 = 4

but I would advise against that.