Python: Trick of the Day

Let's say you have a function that makes use of a global. (Pretend for a moment that global isn't a dirty word.) Let's say you want to define that global within that function, but only if it doesn't already exist. You can use "globals()" and "setdefault" together in the following, fun one-liner:
x = globals().setdefault("x", 0)
This will get the value of the global x. If x didn't already exist, it'll be initialized to 0.

Comments

DeadWisdom said…
Nice!

Globals in Python are really just module-level variables. Nothin' wrong with that.
Anonymous said…
This comment has been removed by a blog administrator.