Scoping Rules

Local vs. Global Scope

  • Functions execute within a local and global scope.
  • Local scope is just the function body.
  • Global scope is the module in which the function was defined.
  • Variable lookups first occur in local scope, then in global scope.
  • All variable assignments are made to the local scope.
     x = 4
     def foo():
         x = x + 1           # Creates a local copy of x
     foo()
     print x                 # Outputs '4' 

The global statement

  • Declares a variable name to refer to the global scope.
     def foo():
         global x
         x = x + 1          # Modifies the global x
     
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 82
July 17, 2000, beazley@cs.uchicago.edu
>>>