In this article I'd like to describe the difference between three built-in methods: globals(), locals() and vars() (original link). Also I'd like to show some examples of their usage.
globals() always returns the dictionary of the module namespace
locals() always returns a dictionary of the current namespace
vars() returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument
Let's see an example of theese functions in different namespaces. I have the module bla.py with following content:
def __init__(self, id):
self.id = id
print "Class locals:\t%s" ...
1. Create a new variable
Now let's see the usage of these functions.
The first one and the most interesting is defining of a new variable:
>>> globals()['new_var'] = 1
2. Searching for needed form
And here is another example from Django framework which I used. Let's assume that we have a page with a few objects. And we want to add or edit objects on the same page. For example, we use pop-up window. We want to request needed form from view. We have classes for them and models that describes these objects. Each button on page will send the model name, which object we want to add/edit.
So, for example we have models: