Modifying Variables Out of Scope
00:00 When you want to modify variables, then you need to be aware of the scope that the variable you need to modify is in. Sometimes, a function is able to modify a variable outside of its local scope, and sometimes it is not.
00:17 So, how can you know whether it’s possible to modify a variable outside the function’s local scope? Well, a function can never modify an immutable variable outside its local scope,
00:34 and a function is able to modify a mutable variable outside its local scope in place.
00:44 Let’s start with an example that shows you it is not possible for a function to redefine the value of a variable that is already defined outside its scope.
00:58
This module declares a variable called x
and it assigns a value 20
. Then inside the function f()
, the function declares another variable x
to a value 40
, after which it prints x
. Now, when you load the module and call the function f()
, you will see that the value of x
is 40
, but when you look at the value of x
itself, then you see that the value of x
is still 20
.
01:35
That is because when this assignment is executed, a new local reference to an integer object whose value is 40
is declared in the local namespace of the function f()
and the value of x
in the global namespace is not affected at all. Out of scope objects of a mutable type, on the other hand, can be modified in place.
02:06
In this example, a list—which is a mutable object—is created in the global scope. And the first item of this list is replaced with another value in the function f()
. After running f()
and looking at my list,
02:27 you will see that the contents of the list changed.
02:33 But if the function tries to replace the list entirely, then it will create a new object in the local scope and won’t modify the list that was created in the global scope.
02:46
So, after running f()
and looking at my list, you will see that the list hasn’t changed at all.
02:57 But what if you really need to modify an immutable value in the global scope? We will have a look at that in the next lesson.
Become a Member to join the conversation.