3

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?

S Wang
  • 213
  • 3
  • 11
  • 2
    there is no variables in `Python`: just names and objects – Azat Ibrakov May 29 '17 at 03:32
  • [this great post](https://nedbatchelder.com/text/names.html) can give you an explanation of what is going on – Azat Ibrakov May 29 '17 at 03:34
  • 1
    @AzatIbrakov: From that post: "Myth: Python has no variables." Variables don't have to work like C variables to use the name. You might prefer the "name" name, but saying Python doesn't have variables is wrong. – user2357112 May 29 '17 at 03:36
  • @user2357112: ok, `Python` has no variables like most people used to think of them – Azat Ibrakov May 29 '17 at 03:40
  • @AzatIbrakov: thx for the link, I've just read it through, but apart from what user2357112 has pointed out (Python does have variables) there seems nothing new in there, and I think I offer a much clearer description in my question (from the aspect of variable and object). – S Wang May 29 '17 at 03:49

3 Answers3

2

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

user2357112
  • 260,549
  • 28
  • 431
  • 505
2

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.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
  • Interesting code snippet. I think the error arises from name collision in the same scope. In `x = x + 1`, the lhs x causes a new local variable x to be created in this local scope. And as a result, the rls x would refer to this local x, instead of searching all the way to the global scope. – S Wang May 29 '17 at 05:43
  • @swang try it with just `x + 1` without assignment then – Jared Goguen May 29 '17 at 18:15
0

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.

Anson Hwang
  • 117
  • 1
  • 8