Python

What is the difference between global and nonlocal in Python?

January 20, 2022

What is the difference between global and nonlocal in Python?

In this article, we’ll learn the difference between global and nonlocal in Python, with practical examples and when we’ll use each of them.

difference between global and nonlocal cover

Hey you all programmers, okay? Let’s learn more about Python!

The big difference between global and nonlocal is that global refers to the global scope.

The nonlocal declaration refers to the local scope above the current scope.

The global scope would be the highest point in the code, where we are outside functions, for example

Here’s a way to use global:

a = 1

def printGlobalVariable():
 global a
 print(a)

def printLocalVariable():
 a = 5
 print(a)

printGlobalVariable()
printLocalVariable()

This is the retrun:

1
5

The first function used the variable that is globally declared

So we understand the global scope as what would be above all other instructions.

Understand above as hierarchically, as it can be anywhere in the code, as long as outside functions and classes

Although these variables are usually declared in the first lines

As for nonlocal, we must create a scope within a scope

That is, a function within a function, for example

See a practical example:

def testFunction():
 x = 1

def printNonLocal():
 nonlocal x
 print(x)

def printLocal():
 x = 2
 print(x)

printNonLocal()
printLocal()
testFunction()

And this is the following return:

1
2

So in this way, we create two scopes, the TestFunction function is a larger scope than the other two

Becoming the nonlocal scope for printNonLocal and printLocal

But we only used the instruction in printNonLocal, which did the proposed

When to use each approach part of the program logic

Do we need to access the global variable? Or a scoped variable above?

These are the questions you should ask, before using each of the instructions.

Conclusion

In this article we learned the difference between global and nonlocal in Python

Basically global is the highest level scope hierarchically in the program, i.e.: outside functions and classes

And the nonlocal is a scope above where it was declared

Want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x