[Python] global vs nonlocal

고승우·2023년 10월 22일

When you working with Python functions, you may across the terms of global and nonlocal. In my case, I had made a big mistake in the middle of live coding test. Let's exlpore the difference between global and nonlocal keyword.

Global Variables

A global variable is a variable that can be accessed from both inside and outside of functions. However, when it comes to modifying a global variable, a specific keyword is required. We will discuss this modifying keyword global. Such variables can be manipulated at the module level. Let's examine the following code."

a = 10
def print_a():
	a = 20
	print(a)

print_a()	# 20
print(a)	# 10

Internally Python assumes that any name assigned within a function is local to that function. Therefore, the local name shadows its global variable.

Nonlocal Variables

Nonlocal variables is a variable that is defined in the enclosing function and can be accessed from nested functions. This means that the variable can be neither in the local nor the global scope. Maybe we can define nonlocal variables is non-global variable that can be used in nested function.

# outside function 
def outer():
    message = 'local'

    # nested function  
    def inner():

        # declare nonlocal variable
        nonlocal message

        message = 'nonlocal'
        print("inner:", message)	# nonlocal 

    inner()
    print("outer:", message)	# nonlocal
outer()

global keyword

We know that we can access global variables anywhere within a Python module. However, changing global variable can be dangerous. Consider a situation that function A unintentionally changes a global varible, and then function B access varaible a without being aware of the change. To address this potential issue, python requires us to explictly declare that "I know I'm trying to change global variable". In other words, before altering global variable, we must use global keyword.

a = 10
def print_a():
	global a
	a = 20
	print(a)

print_a()	# 20
print(a)	# 20

nonlocal keyword

The nonlocal keyword is used to handle variables inside nested functions where the variable should not belong to the inner function. This keyword work same as global keyword. But, It's different with global varialbe. As definition of nonlocal and global variable differs, using nonlocal keyword when attempting to modify a global variable can lead to unexpected issues.

a = 10
def print_a():
	nonlocal a # Error: No binding for nonlocal "a" found
	a = 20
	print(a)

print_a()	# 20
print(a)	# 20

Similar with global keyword, nonlocal explicitly specify that I want to modify the nonlocal variable from the enclosing scope.

profile
٩( ᐛ )و 

0개의 댓글