Actually there is a difference in Python ehre:
If a variable named some_var
is not defined you can't access it to know it does not exist -
you will get a NameError exception.
This is so by design: undefined variable names do not have an "undefined" or "null" value, they raise an Exception, and that is one of the greates differences from Python to most dynamic typed languages.
So, it is not Pythonic to get to a statement where some_var
might or not be defined. In a good program it would have been defined, even if to contain "None" or "False" -
In that case the "or" idiom would work, but the recommended way to handle it s to use the expression if
like in:
return some_var if some_var else "some_var contains a False Value"
If you happen tohave code where some_var
might not be defined, and cannot for soemr eason change that, you can check if the string "some_var" exists as a key in the dicitonary of localv ariables, returned by locals()
to know wether it was defined or not:
return some_var if "some_var" in locals() else "some_var was not defined"
That is not the most pythonic way either - having to deal witha variable that my not be defined is exceptional in Python code. So the best pratice would be to try to use the vars contents inside a try cause, and catch the "NameError" exception if the var does not exist:
try:
return some_var
except NameError:
return "some_var not defined"