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
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
This is a very different style of programming, but I always try to rewrite things that looked like
bar = None
if 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.
IfLoop's answer (and MatToufoutu's comment) work great for standalone variables, but I wanted to provide an answer for anyone trying to do something similar for individual entries in lists, tuples, or dictionaries.
Dictionaries
existing_dict = {"spam": 1, "eggs": 2}
existing_dict["foo"] = existing_dict["foo"] if "foo" in existing_dict else 3
(Don't forget the comma in ("foo",) to define a "single" tuple.)
The lists and tuples solution will be more complicated if you want to do more than just check for length and append to the end. Nonetheless, this gives a flavor of what you can do.
Instead of having NameError, this solution will set var1 to default value if var1 hasn't been defined yet.
Here's how it looks like in Python interactive shell:
>>> var1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'var1' is not defined
>>> var1 = locals().get("var1", "default value 1")
>>> var1
'default value 1'
>>> var1 = locals().get("var1", "default value 2")
>>> var1
'default value 1'
>>>