Summary: in this tutorial, you’ll learn how Python variable scopes work. After the tutorial, you’ll have a good understanding of built-in, local, and global scopes.
Introduction to Python variable scopes #
When you assign an object to a variable, the variable will reference that object in the memory. It’s saying that the variable is bound to the object.
After the assignment, you can access the object using the variable name in various parts of your code. However, you cannot access the variable everywhere in the code.
The variable name and its binding (name and object) only exist in specific parts of your code.
The part of the code where you define the name/binding is called the lexical scope of the variables.
Python stores these bindings in something called namespaces. Every scope has its own namespace.
You can think that a namespace is a table which contains the label and the reference that the label is bound to.
Global scopes #
The global scope is the module scope. The global scope spans a single Python source code file only.
Python doesn’t have a truly global scope that spans across all modules except for the built-in scope.
The built-in scope is a special scope that provides globally available objects such as print, len, None, True, and False.
Basically, the built-in and global variables exist everywhere inside a module.
Internally, global scopes are nested inside the built-in scope: