Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit evaluation assignment in python?

Tags:

python

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?

like image 505
Eduard Florinescu Avatar asked Nov 13 '12 14:11

Eduard Florinescu


3 Answers

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'
like image 79
Martijn Pieters Avatar answered Oct 23 '22 14:10

Martijn Pieters


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.

like image 32
mgilson Avatar answered Oct 23 '22 12:10

mgilson


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.

like image 37
Zero Piraeus Avatar answered Oct 23 '22 14:10

Zero Piraeus