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'
>>>