What does it mean that a region is defined statically and used dynamically?

This is an excerpt from Python docs for classes I'm trying to understand:

A scope is a text area of ​​a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified name reference is trying to find a name in the namespace.

Although areas are defined statically, they are used dynamically.

I did not quite understand what the author meant by the scope of this definition, which text area of ​​the program and which means that the areas are defined statically and dynamically used. I have an intuitive understanding of the field, but I would like to fully appreciate the definition of documents. If someone was so kind as to clarify what the author had in mind, that would be very grateful.

+7
scope python namespaces class
source share
1 answer

"Defined Statically"

There is a global scope and scope (let the third be ignored).

Whether the variable is global or local in some function 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 statically determined that func1 has one local variable and that its name is c . Statically, because it runs immediately after the function is created, and not later, when any local variable actually accesses it.

What are the consequences of this? For example, this function does not work:

 a = 1 def func2(): print a # raises an exception a = 2 

If the scope was dynamic in Python, func2 would print 1. Instead, according to print a , it is already known that a is a local variable, so global a will not be used. Local a will not be used as it is not yet initialized.

"Used dynamically"

From the same document :

On the other hand, the actual name lookup is performed dynamically, at run time - however, the language definition evolves towards static name resolution when compiling, so don't rely on dynamic name resolution! (In fact, local variables are already defined statically.)

Global variables are stored in a dictionary. When the global variable a opened, the interpreter searches for the key a in this dictionary. This is a dynamic use.

Local variables are not used in this way. The interpreter knows in advance how many variables the function has, so it can give each of them a fixed location. Then access to the xy local variable can be optimized by simply taking the “second local variable” or the “fifth local variable” without actually using the variable name.

+6
source share

All Articles