Python goes according to a very simple principle:
- When accessing a name, it is first resolved in the current namespace, and if it cannot be found there, it is resolved in the parent namespace (and so on, until you reach the outer, global namespace).
- When assigning a name, it is added to the current namespace, possibly shadowing names in the parent namespace.
- To avoid the previous behavior, you can declare it global, and then it won't be added to the current namespace. But this doesn't make it global in another namespace!
Moreover, if you want to use the global g, you have to declare so in the beginning of the namespace.
For the code above, you actually get the following error:
>>> def b():
SyntaxError: name 'g' is used prior to global declaration