In this tutorial, we will first update on variable scopes, so that we can properly understand how global, local variables work and not Python locations.
Local variables
Example:
x = "outside"
def internal():
# This is the local variable!
x = "internal"
return x
print("outside:", x)
print("inside:", inside())
outside: outside
inside: inside
Notice how reassigning the inner x does not change the outer x. As you can see, variables declared inside a function (and other types of scopes such as classes and class methods) are local to its scope. In other words, they don't interact with anything out of scope!
Here is one more example:
x = "outside"
def internal():
x = "internal"
def same_inside():
# x is local to inner(), which encompasses same_interior()
# then this works
print("same_inside:", x)
# x = 10 <-- This will break it,
# since x becomes local to even_inner
# # What will make the previous statement
# be interrupted as the inner x is unassigned
# # inside even_inner
return x # Note that this still works!
return same_inside()
print("outside:", x)
print("inside:", inside())
Python global and nonlocal (not local)
There is a way to control which scope variables fall under. That way you can have variables that would be local affecting the global variable (or a variable from the parent scope)
x = "unaffected"
def internal():
# This sets all assignments to the name 'x'
# to match the assignments
# for global x
global x
x = "affected"
print("before interior:", x)
internal()
print("after interior:", x)
nonlocal is something similar but different.
Where global allows you to assign variables in the global scope. nonlocalinstead lets you go 'just one step'. Allowing you to change local local variables to a parent scope instead of the global scope! It's a good way to encapsulate variables and keep things from 'spreading out', so to speak.
It is best illustrated with an example:
x = "global"
def inside():
x = "inside" # This sets a local variable to internal
print("before same_inside:", x) # Check here
def same_inside():
nonlocal x # Now we can reassign the x that is local to internal!
x = "same_inside" # what we do here
same_interior() # This defines "interior" -> "same_interior"
return x # And returns "same_inside"
print("global:", x)
print("after same_interior:", interior())
print("global preserved:", x)
Post a Comment
0Comments