The global keyword

To avoid this shadowing of names in the global scope, we need to instruct Python to resolve the name count in the set_count() function to the count defined in the module namespace. We can do this by using the global keyword. Let's modify set_count() to do so:

def set_count(c):
global count
count = c

The global keyword simply introduces a binding in the local scope to a name from the global scope.

Quit and restart the Python interpreter to exercise our revised module:

>>> from scopes import *
>>> show_count()
count = 0
>>> set_count(5)
>>> show_count()
count = 5

It now demonstrates the required behaviour.

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

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