[Tutor] Question about why a list variable is apparently global.

Steven D'Aprano steve at pearwood.info
Thu Nov 27 16:33:07 CET 2014


On Thu, Nov 27, 2014 at 09:00:48AM -0600, boB Stepp wrote:

> Level of indentation is the key? Can you give me an example, not
> involving functions, where a variable is defined at an "inner" level
> of indentation, but is not accessible at the outermost level of
> indentation? 

Classes and functions introduce a new scope.

py> x = "outer"
py> class Test:
...     x = "inner"
...
py> x
'outer'

Notice that the outer "x" is unchanged, while the inner "x" is only 
accessible by specifying the class (or an instance) first:

py> Test.x
'inner'

But there is a subtlety that you may not expect:

py> class Tricky:
...     print(x)
...     x = "inner"
...     print(x)
...
outer
inner


So although classes introduce a new scope, they are not like functions. 
In a function, the above would lead to an error (try it and see).

* Every module is a separate scope.

* `def` and `class` introduce new scopes.

* Other indented blocks (for, while, if etc.) do not.

* But lambda expressions do.

* Generator expressions have their own scope too.

* In Python 3 only, so do list comprehensions (and dict and set 
  comprehensions). But not in Python 2.



-- 
Steven


More information about the Tutor mailing list