Navigating Namespaces and Scope in Python (Summary)
Virtually everything that a Python program uses or acts on is an object. Even a short program will create many different objects. In a more complex program, they’ll probably number in the thousands. Python has to keep track of all these objects and their names, and it does so with namespaces.
In this course, you learned:
- What the different namespaces are in Python
- When Python creates a new namespace
- What structure Python uses to implement namespaces
- How namespaces define scope in a Python program
- How the LEGB rule applies to scope
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00 In this course, you gained a solid understanding of namespaces and scope in Python. We started by looking at the built-in, global, local, and enclosing namespaces that are used by the Python interpreter. Next, you learned about the different scopes in Python and you learned the LEGB rule you can use to figure out in which scope something is located.
00:28
Finally, you learned how to modify variables out of scope by using the global
and nonlocal
keywords or by modifying mutable objects in place.
00:41 I hope you enjoyed this course and you will join us again in the future here at Real Python.
RobyB on March 4, 2021
I agree with you Alan :)
Dirk on March 22, 2021
Short and sweet. I liked it a lot.
mckown on July 14, 2021
Excellent! I think Alain’s review is spot on.
I finished a course on import before this and heard (again) that one should not use “from module import *“. Something clicked while going through this course and when I imported asterisk from tkinter, I was able to see all the module’s functions, constants, etc. crowding into the globals space. This would be a good demo (in this course or the import course).
Fantastic job, Johan and team!
Become a Member to join the conversation.
Alain Rouleau on March 3, 2021
Great explanation of namespaces and the concept of scope, thanks!
I’ve seen many people try to explain these Python concepts over the years. But this is one of the best tutorials that I’ve seen. Kudos! I like how you used simple functions to explain things, introduced the
globals()
function, andnonlocal
for enclosed functions as well. Not many people know about those.Plus, use of the equal sign in f-strings was a nice touch. Definitely going to use that in the future. Not to mention, the
"i"
command line option. Pretty sure 99% of people don’t know about that feature either which allows you to start an interactive session and import a module ALL in one step. Very handy.Keep up the good work!