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
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
This is a very different style of programming, but I always try to rewrite things that looked like
into just:
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
Returns
{"spam": 1, "eggs": 2, "foo": 3}
Lists
Returns
["spam", "eggs", "foo"]
Tuples
Returns
("spam", "eggs", "foo")
(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.
I'm also coming from Ruby so I love the syntax
foo ||= 7
.This is the closest thing I can find.
I've seen people do this for a dict:
Upadate: However, I recently found this gem:
If you like that, then for a regular variable you could do something like this:
You should initialize variables to None and then check it:
Which can be written in one line as:
or using shortcut (but checking against None is recommended)
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 thisbut I would advise against that.
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.
If you mean a variable at the module level then you can use "globals":
but the common Python idiom is to initialize it to say
None
(assuming that it's not an acceptable value) and then testing withif var1 is not None
.