glithc
glithc

Reputation: 135

What does it mean that a scope is determined statically and used dynamically?

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.

I didn't quite comprehend what the author meant by a scope from this definition, what's a textual region of a program, and what it means that scopes are statically determined and dynamically used. I have an intuitive understanding of a scope, but would love to fully appreciate the docs definition. If someone would be so kind as to elaborate what author had in mind it would be greatly appreciated.

Upvotes: 12

Views: 672

Answers (1)

zvone
zvone

Reputation: 19352

"Defined Statically"

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.

For example:

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.

"Used Dynamically"

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.

Upvotes: 10

Related Questions