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.
Wednesday, December 06, 2006
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: