Python – Global and local variables in Python classes

Global and local variables in Python classes… here is a solution to the problem.

Global and local variables in Python classes

x = "xtop"
y = "ytop"
def func():
    x = "xlocal"
    y = "ylocal"
    class C:
        print x  #xlocal  of course
        print y  #ytop  why? I guess output may be 'ylocal' or '1'
        y = 1
        print y  #1  of course
func()
  1. Why are x and y not the same here?

  2. If I replace class C with a function scope I get UnboundLocalError: local variable 'y' referenced before assignment, what is the difference between a class and a class and the functionality in this case?

Solution

This is because the scope of

class C is actually different from the scope of def func – and the different default behavior of python scopes.

This is basically how Python looks up variables

  • View the current scope
  • If the current scope does not exist, -> uses the closest closed scope
  • If the current scope has it, but not yet defined> uses the global scope
  • If the current scope has it, and -> is already defined, use it
  • Otherwise explode

(If you remove ytop, you get a NameError: name 'y' is not defined.)

So basically, when the interpreter looks at the code section below, it goes

class C:
    print(x) # need x, current scope no x  -> default to nearest (xlocal)
    print(y) # need y, current scope yes y -> default to global (ytop)
             #         but not yet defined 
    y = 1
    print(y) # okay we have local now, switch from global to local

Consider the following scenario

1) class C:
    print(x)
    print(y)

>>> xlocal
>>> ylocal

2) class C:
    y = 1
    print(x)
    print(y)  

>>> xlocal
>>> 1

3) class C:
    print(x)
    print(y)
    x = 1

>>> xtop
>>> ylocal

Related Problems and Solutions