Identical names in global and local scope

Very occasionally we need to rebind a global name at module scope from within a function. Consider the following simple module:

count = 0

def show_count():
print(count)

def set_count(c):
count = c

If we save this module in scopes.py, we can import it into the REPL for experimentation:

$ python3
Python 3.5.0 (default, Nov 3 2015, 13:17:02)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from scopes import *
>>> show_count()
count = 0

When show_count() is called Python looks up the name count in the local namespace (L). It doesn't find it so looks in the next most outer namespace, in this case the global module namespace (G), where it finds the name count and prints the referred-to object.

Now we call set_count() with a new value:

>>> set_count(5)

We then call show_count() again:

>>> show_count()
count = 0

You might be surprised that show_count() displays 0 after the call to set_count(5), so let's work through what's happening.

When we call set_count(), the assignment count = c creates a new binding for the name count in the local scope. This new binding refers, of course, to the object passed in as c. Critically, no lookup is performed for the global count defined at module scope. We have created a new variable which shadows, and thereby prevents access to, the global of the same name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset