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
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.
global
/nonlocal
declaration or use except UnboundLocalError
(and accept that the variable will be local and a globally-set value will be ignored).
except
), var1
is a local variable unless the snippet is at module (that is, global) level or there is a line global var1
. Accessing a not-yet-assigned local variable raises UnboundLocalError
instead of NameError
(which is reserved for global names).
>>> issubclass(UnboundLocalError, NameError) True
Sep 8, 2011 at 2:01
var1 = var1 or 4
can hurt you if var1 was 0
as 0
is a falsey value and therefore 0 or 4
evaluates to 4
which is not what you won't in this case. You can check which other things evaluate to "false" in docs.python.org/2/library/stdtypes.html#truth-value-testing
Oct 21, 2015 at 22:01
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 = 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.
bar = "Baz" if foo() else "Quux"
False
, 0
, ''
, []
, {}
). Better to say x = y if x is None else x
.
Apr 16, 2019 at 10:36
I'm also coming from Ruby so I love the syntax foo ||= 7
.
This is the closest thing I can find.
foo = foo if 'foo' in vars() else 7
I've seen people do this for a dict:
try:
foo['bar']
except KeyError:
foo['bar'] = 7
Upadate: However, I recently found this gem:
foo['bar'] = foo.get('bar', 7)
If you like that, then for a regular variable you could do something like this:
vars()['foo'] = vars().get('foo', 7)
Here is the easiest way I use, hope works for you,
var1 = var1 or 4
This assigns 4
to var1
only if var1
is None
, False
or 0
NameError: name 'var1' is not defined
.
Sep 27, 2022 at 20:22
var1
if it's not defined, not if it has a falsey value.
One-liner solution here:
var1 = locals().get("var1", "default value")
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'
>>>
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
Returns {"spam": 1, "eggs": 2, "foo": 3}
Lists
existing_list = ["spam","eggs"]
existing_list = existing_list if len(existing_list)==3 else
existing_list + ["foo"]
Returns ["spam", "eggs", "foo"]
Tuples
existing_tuple = ("spam","eggs")
existing_tuple = existing_tuple if len(existing_tuple)==3 else
existing_tuple + ("foo",)
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.
If you mean a variable at the module level then you can use "globals":
if "var1" not in globals():
var1 = 4
but the common Python idiom is to initialize it to say None
(assuming that it's not an acceptable value) and then testing with if var1 is not None
.
locals()
breaks on globals, and I don't think either works with nonlocals. To fix that, one would have to emulate the whole scoping rules or write the code assuming one of both.
defvar
of common lisp, my wild guess was that it was looked for at global level