Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Getting to Know the Global Scope

00:00 The global scope, the scope above all scopes, the one scope to rule them all, its presence extends throughout all the lands of Middle … I mean throughout all the scopes of your program.

00:11 Also known as the module scope, the global scope exists as the outermost scope of your Python script or module. It contains the variables, functions, and classes defined at the top level of the program.

00:24 It makes all of these names accessible anywhere in that program, and it is created when the program starts and lasts until it ends.

00:32 It’s impossible to talk about the global scope without also touching on the global statement and the globals() function—don’t mix them up.

00:40 The global statement is kind of like the nonlocal statement, but for global names. It can be used to bring global variables into a local scope and enables the modification of a global variable from within a function.

00:52 The globals() function, on the other hand, is similar to the locals() function. It’s a built-in function and it returns a reference to the current global scope, i.e., the namespace dictionary.

01:03 But unlike locals(), you can use this dictionary to mutate the scope itself. Onto the REPL to write some code.

01:12 Start by running dir() to get a quick view of the names of the global scope. And you get a list of names Python uses internally. To look at the full dictionary or namespace of names, call globals().

01:24 A lot more output, right? Something that might be familiar to you is that first element under __name__. When you run a Python program, the script that is executed directly, the entry point will have its __name__ variable set to the string __main__ in the global scope.

01:41 This also applies to the REPL. Moving on, go ahead and create a variable at the top level. var = 100 and call dir(),

01:51 and there it is at the end of the list, var. You can even modify var directly from the dictionary returned by globals().

01:59 Call globals(), grab var with bracket accessors, and set it to 500. And inspect var, it’s 500.

02:06 And just a warning, this is not an advisable way of modifying variables. Okay, now how do global variables behave in functions? Create a function and have it return var: def func(): return var, the global variable.

02:23 Call func(), and it returns 500. func() has no problem reading var and returning its value. Where things get a little bit hairy is when it comes to assignment.

02:32 And let me just clear the screen here, clear. Try writing another version of func() where you print() the global variable var, and then create a local version also called var: def func(): print(var)

02:48 var = 200.

02:50 So you might think the first reference to var is going to be a global reference, and the second will just create a local variable. So do you think this works? Go ahead and try calling func(),

03:03 and you get an Unbound ‘LocalError: cannot access local variable var` where it is not associated with the value. Why does this happen? Because var is assigned within the body of func(), Python treats it as a local variable everywhere inside the function.

03:17 And when you try to print() it because it’s part of the local scope but hasn’t been assigned a value yet, you get this error.

03:24 For another example, try creating a function called increment() that attempts to increment var: def increment():

03:32 var = var + 1. Do you think it’s going to work this way? Call increment(). And again, another UnboundLocalError happening for the same reason as before.

03:44 So is there a way around this? Yes, there is: the global statement. Let me clear the screen again.

03:52 Define increment(): global var. And the global statement here makes var modifiable within the local scope of this function.

04:00 And trying again with var = var + 1, check the value of var first. We’re still working with the same REPL session, so it’s still got the value of 500.

04:10 And now call increment()

04:13 and the moment of truth, check var again and 501. It works, var was modified by the increment() function.

04:22 Behold the power of the global statement. Alright, this is the point in the afterschool special where I do have to get serious. You just learned multiple ways to modify global variables from almost anywhere in your code.

04:34 And I know I make it look cool, but in most cases, modifying global variables is a bad programming practice. It can lead to brittle code that’s difficult to debug.

04:44 The code is harder to understand. Hidden dependencies can be introduced, and even a small change in one area of a program can end up breaking seemingly unrelated functionality.

04:55 So generally, it’s recommended you stick to using self-contained functions with local names. Err towards minimizing reusing names even across scopes, and use global names for constant values that never need to change while the program is running.

05:11 Alright, three scopes down, one to go. Next we have last but not least, the built-in scope.

Become a Member to join the conversation.