Python scope
Scopes
- The enclosing module is a global scope.
- The global scope spans a single file only.
- When you create a variable in a function which has enclosing function, the scope of enclosing function is called nonlocal.
- Assigned names in a function are local unless declared with keywords
global
or nonlocal
.
- Each call to a function creates a new local scope.
- Most statement blocks (like
if
or for
loop) do not create scope as in other languages as go or c. The below two blocks are exceptions, as they do create scope:
- Comprehension variables: like X in
[x for x in l]
- Exception variables: like X in
except E as X
Hierarchy