Scope#
When you type a name its definition (and therefore its meaning and usage) as used by the Python interpreter depends on where it is defined. To determine where a name is defined, Python
depends on
In Python, a variable is only available from inside the region it is created. This is called scope. There are five different scopes:
- local scope: names defined inside a function (or lambda)
- enclosing scope: names in the local scope of enclosing functions (nested functions)
- function inside function:
- global scope: names defined at the top level of a module (or declared global with the global keyword)
- built-in: reserved names preassigned by Python (e.g., import, def, for)
Table of Contents
Local Scope#
These are names defined inside a function or method.
local_scope.py # example of local scope def local_example(): # define a variable 'x' whose scope is local to the function x = "I'm local" print(x) # if we call local_example() the result will print "I'm local". local_example() # the following would result in an error, as x is not defined outside the function print(x)Enclosing Scope#
These are names defined in the local scope of an enclosing function.
enclosing_scope.py # example of enclosing scope def outer(): # we define a variable 'x' within the scope of the outer() function x = "I'm in the enclosing scope" def inner(): print(x) # accesses x from enclosing function # if the outer() function is called, inner() is called too inner() # we call the outer() function outer()