Ruby supports this:
name = name || "default"
If I try it in python:
name = name or "default"
Interpreter reports:
NameError: name 'name' is not defined
What is the equivalent of the short circuit evaluation assignment in python?
If you actually defined name
it'd work:
name = None
name = name or 'default'
The short-circuiting is independent from actually having to define your variables. Generally, name
has been pulled from somewhere but is an empty (falsy) value:
name = somefunction('name') or 'default'
name = globals()['name'] if 'name' in globals() else 'default'
or, more succinctly:
name = globals().get('name','default')
Substitute locals()
inside functions.
Possibly it would be better to just try/except
:
try:
name
except NameError:
name = 'default'
As a side note, I would never use either of these idioms in my code. (Of course, I wouldn't use the other idioms from Javascript or Ruby that you mentioned). I'd make sure my variables were declared to the default values at the outset and then change them to non-default values as the need arises.
It's a horrible, horrible idea, but ...
name = globals().get("name", locals().get("name", "default"))
... will do what you want (while leaving you in the dark as to whether you now have a global or local variable), and is ugly enough to hopefully put you off trying it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With