Scope in Python

2

I follow a book about python but I found a doubt about the scope, I have the following code:

pi = 3.14
def crear_area(pi = pi):
    def area(r):
        return pi*r*r
    return area

area = crear_area(10)
print(area(10))  #valor de retorno es 314.5
pi = 12
print(area(10))  #valor de retorno es 314.5

They can explain to me why the change of the object pi did not affect the result, so I see python if it handles a static scope.

    
asked by julian salas 13.03.2016 в 07:38
source

1 answer

5

This is an example of closures ( closure en English) and how they work.

When you define the function crear_area , you are creating a local variable to that function named pi and with default value pi (global):

def crear_area(pi = pi):

Now, within that function, you are defining a second function area that is returned as result / object:

pi = 3.14
def crear_area(pi = pi):
    def area(r):
        return pi*r*r
    return area

As the scope ( scope in English) of area is exclusively within crear_area and its variables, it does not matter that you change the value of the global variable pi , because area will always use the local variable pi of crear_area that had a value of 3.14 at the time of its definition.

And that is the reason why, even if you change the value of pi (global), print(area(10)) will always return the same: the internal variables maintain their value within the closure.

If you want them to have different values, then you would have to create a new area by passing pi as a parameter (so you would not use the default value but the new one you pass):

pi = 3.14
def crear_area(pi = pi):
    def area(r):
        return pi*r*r
    return area

area = crear_area()
print(area(10))  #valor de retorno es 314.0
pi = 3  #referencia a Futurama
area = crear_area(pi)
print(area(10))  #valor de retorno es 300

In this way you would be creating a new environment with new variables and the values would be "reset" for area .

Another possible alternative would be to not define the local variable pi and so the global one would always be used, obtaining different values:

pi = 3.14
def crear_area():
    def area(r):
        return pi*r*r #ahora este pi es la variable global
    return area

area = crear_area()
print(area(10))  #valor de retorno es 314.0
pi = 3  #referencia a Futurama
print(area(10))  #valor de retorno es 300
    
answered by 13.03.2016 в 18:47