This is an excerpt of Python docs for Classes I'm struggling to understand:
A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
Although scopes are determined statically, they are used dynamically.
There is global scope and local scope (let's ignore the third one).
Whether a variable is global or local in some function is determined before the function is called, i.e. statically.
a = 1 b = 2 def func1(): c = 3 print func1.__code__.co_varnames # prints ('c',)
It is determined statically that
func1 has one local variable and that its name is
c. Statically, because it is done as soon as the function is created, not later when some local variable is actually accessed.
What are the consequences of that? Well, for example, this function fails:
a = 1 def func2(): print a # raises an exception a = 2
If scopes were dynamic in Python,
func2 would have printed 1. Instead, in line with
print a it is already known that
a is a local variable, so the global
a will not be used. Local
a wont be used either, because it is not yet initialized.
From the same document:
On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.)
Global variables are stored in a dictionary. When global variable
a is accessed, the interpreter looks for key
a in that dictionary. That is dynammic usage.
Local variables are not used that way. The interpreter knows beforehand how many variables a function has, so it can give each of them a fixed location. Then, accessing local variable
xy can be optimized by simply taking "the second local variable" or "the fifth local variable", without actually using the variable name.