Saturday, April 28, 2012

Hidden methods in Python

How would one access variables programmatically in Python? Well, there are two dictionaries, one returned by globals() which contains all global variables, and one returned by locals() which contains all local variables. To demonstrate:
>>> a = 4
>>> locals()['a']
>>> locals()['b'] = 'spam'
>>> b
Declaring a variable is the same thing as accessing its name in the locals() dictionary (or the globals() dictionary if the variable is declared global).
But what if we do this:
class a:
    b = 4
locals()['a.b'] = 'spam'
What will be the value of a.b?