Python local variables statically determined?

Question:

Python tutorial says that (https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces)

In fact, local variables are already determined statically.

How to understand this? Based on what I knew static means that the type of a variable is determined at compile time. But it is not true considering for example

x = 1
x = 'str'

where the variable x is dynamically bound to objects of type int or string at runtime.

Reference: Is Python strongly typed?

Asked By: S Wang

||

Answers:

Their existence, and whether a variable lookup is local or global, is determined at compile time.

Answered By: user2357112

In addition to the other answer, consider the error produced by the following code.

x = 1

def function():
    y = x + 1
    x = 3

function()

This will produce an error like “UnboundLocalError: local variable ‘x’ referenced before assignment” because it is determined that x is a local variable in function so it should be found in the local scope, negating the global definition.

Answered By: Jared Goguen

There is a statement in that document too.

if not declared nonlocal, those variables are read-only (an attempt
to write to such a variable will simply create a new local variable in
the innermost scope, leaving the identically named outer variable
unchanged).

In Jared Goguen’s code, clause x = 3 will let Python see x as local during compile.

Answered By: Anson Hwang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.