Variables and scope
Compare a module binding and a local binding
Scope tells you which part of a program a name belongs to. Functions can read a module-level name. A new assignment inside a function can create a local name.
limit = 10
func read_limit():
return limit
func local_limit():
limit = 3
return limit
print(read_limit())
print(local_limit())
print(limit)
10
3
10
The local assignment in local_limit() does not change the module’s limit. This lets a function use temporary names safely.
A module or function introduces a lexical scope. Control-flow blocks share the enclosing scope. Parameters, constants, function declarations and import aliases declare bindings. A plain assignment to a name declares a local if the name has no local or enclosing function binding. The scope of a binding covers its entire function or module, and a read before initialization raises an error.