The suite of statements in a function definition executes with a
local namespace that is different from the global namespace. This means
that all variables created within a function are local to that function.
When the suite finishes, these working variables are discarded.
The overall Python session works in the global namespace. Every
other context (e.g. within a function's suite), there is a distinct local
namespace. Python offers us the
global
statement to
change the namespace search rule.
The
global
statement tells Python that the
following names are part of the global namespace. The following example
shows two functions that share a global variable.
ratePerHour= 45.50
def cost( hours ):
global ratePerHour
return hours * ratePerHour
def laborMaterials( hours, materials ):
return cost(hours) + materials
Warning
The
global
statement has a consequence of
tightly coupling pieces of software. This can lead to difficulty in
maintenance and enhancement of the program. Classes and modules provide
better ways to assemble complex programs.
As a general policy, we discourage use of the
global
statement.