Scope in Python

Updated 14 April 2022

Deeper we go into the Python Mines of Moria, but I promise there is no Balrog here. We now have reached the point of scope and I will steer you smoothly clear. Scope is somewhat notorious, especially when one is a pioneer. It can leave you in wonder sincere, as you'll find certain lines end up sheer.

So let me help spelunk the way. In programming the scope of a name defines the area of a program in which you can unambiguously access that name. Name in this case means variables, functions, objects or classes. A name will only be visible to and accessible by the code if it is within scope. A name can also be referred to as an identifier or a namespace. Namespace is the system Python uses to have a unique name for every variable or method within Python. Python itself maintains namespaces in the form of a Python dictionary.

There are four different levels of scope which are local, enclosed, global and built-in. These are anagrammed to LEGB. Each of these and more will be explored in this guide. The contents of this tutorial with quick links can be seen below.

If this is the first time you have encountered Python a great place to start would be Python Rundown and Main Windows. These will also tell you where to download Python and access online Python emulators. Python is an excellent language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB. These are computing devices that can easily fit on the palm of your hand.

As always if you have any questions, queries or things to add please let us know your thoughts!


Why Scope?

Before there was scope there was only global names. This meant any part of the program could modify any variable at any time. This was how it was in many early programming languages such as BASIC. The greatest disadvantage of this was when creating large programs, it became critical that each and every variable had a unique name. If not major problems would occur as parts of the software start to interact in ways not planned. Thus the programmer would have to remember every variable which would eventually become impossible as codes became increasingly larger.

So now most programming languages use scope to avoid this. Scope prevents you from accessing all the variables in a program at all locations in that program. For Python the ability for a code to access a given name will depend on where exactly that name has been defined. When you can access the value of a given name from your code, this will mean the name is in scope. If you cannot access the name, this will mean the name is out of scope.


LEGB Overview

At any point during the execution of your code there will be a maximum of four Python scope levels. These are local, enclosing, global and built-in (shorthand anagram LEGB) which are explained below. 

A Python under the Scope- Built-in Scope. This is a special Python scope that is created whenever any script is running or a window with interactive programming is open. A window with interactive progamming operating means it is constantly undergoing a read, evaluate, print cycle. The Python IDLE Shell is an example of this. After entering a line of code the results feedback straight away. Some names inside the built-in scope can be found in the guide All the Built-in Functions of Python.
- Global Scope. This is also referred to as module scope. This is a top scope within the Python programming language. This scope contains all the names that you have defined at the top level of a program or module. Names in this scope can thus be accessed from everywhere in your scripts.
- Local Scope. This is also referred to as the function scope. This scope contains all the names that you have defined inside a function. These names are only visible from the code of the function. This scope is created only when the function is called. Many local scopes can exist simultaneously. Each time a function is called a new local scope is made. Even if it is the same function being called again a new local scope will be created. The | lambda | keyword also creates a local scope when it is executed in code.  
- Enclosed Scope. This is also referred to as non-local scope. This is a special scope that exists only for nested functions. A nested function is a function which is defined within another function. The outside/outer function is called the enclosing function. If the local scope is a nested function then the enclosing scope is the scope of the outside/outer function. This scope contains all the names that are defined in the enclosing function. Names in the enclosed scope can be accessed by the nested and enclosing function. More about function can be found in the guide Making Your Own Python Function!

Python has a procedure which it will always follows to lookup names. First it will look through all the names in the local scope, then the enclosing scope, then the global scope and then finally the built-in scope. Below is a great image to visualise this. Now depending on the code there can be fewer levels of scope however there will always be global and built-in layers of scope avaliable in your Python codes. 

The Order in which scope is performed by Python, starting with Local.


LEGB Details Tabulated

There are a number of key details about these scopes, for example which scopes can alter variables in another scope level, which are best demonstrated when tabulised. This table which compares them to each other is seen below. Worth noting, to declare code as global or nonlocal you utilised the keywords | global | and | nonlocal | respectively. More about these keywords can be found in the guide All the Keywords in Python.

Details about what variables can be altered depending on scope level


Scope Script Examples

So let us clarify scope with some code examples. Explanations will be throughout as some of these scripts will work and some will cause Python errors messages to appear. This is to demonstrate the effects that different scopes have on your Python scripts. Thus the following will be a series of scripts created in the Python Programming Window with the Python IDLE Shell seen adjacent.

1. The script below uses the | global | keyword so that the local scope can modify the variable A which exists in the global scope. The local scope exists because a function has been created. The modification occurring to the variable A is adding 2 to the initial value. Normally a function cannot modify a global variable, it can only access it. By using this keyword the code can execute fully. So once this script is run and then once the calling environment calls for this function, the value 3 will be printed back to the calling environment.

This is the same code as before but we have not given the function the capacity to access and modify the variable A by using the global keyword.

 
2. 
This code demonstrates that in Python, by default, a function cannot modify a global variable. This is a good thing as you will not need to remember every variable and create new names for every new variable you make. If any function could modify global variables and then the same variable names were used the codes would be overwriting each other left, right and centre. Chaos! Seen below is a function creation which has a local scope and tries to modify a variable. The variable creation occurs before which is at a global scope. As this does not work an error message appears when the after the script is run and the calling environment calls for the function.

The function is not allowed to access and change the global variable. This is a good thing.

 
3. 
This script demonstrates the global scope being unable to access a local scope variable. Seen below is a  variable that was created within a function. Then this variable is attempted to be called from the global scope. This will always cause an error message to appear in the calling environment because the global scope is attempting to call a variable based inside a local scope which cannot be done.

Global scope attempting to search for variable but cannot find it as it has been defined in a local scope.

  
4. Below is a script where a local scope attempting to modify a variable located inside a different local scope. As this cannot be done a error message displays inside the calling environment. This is a good conceptual example demonstrating that multiple local scopes can exist simultaneously within Python. The amount of local scopes existing simultaneously are limitless. A local scope attempting to modify variable of a different local scope

 
5.
Below is a script that has two functions one nested inside the other. When the code is run and the calling environment calls the external function three things are printed to the calling environment. This is two hello statements from both the internal and external function and a number. This number started life as a variable created inside the external function. Then in the internal (nested) function the variable has been defined nonlocal using the | nonlocal | keyword and then the variable has been modified. Thus a variable that exists in the enclosed scope has been modified by the code inside the nested function by sucessfully utilising the | nonlocal | keyword.Modifying variable that exists in outer function from inner function successfully by utilising the nonlocal keyword

 
6.
Here is code similar to that above, it has two functions one nested inside the other. An attempt is made to modify the variable that was created in the outer function by using code from the inner (nested) function. This is done without using the | nonlocal | keyword to define the variable to have a nonlocal scope. Once the code is run and the calling environment calls for the function it will cause a Python error which can be seen adjacent. 

Attempting to modify a varaible that was created in the outer function from the inner function without using a nonlocal variable.


The Next Step

Importing would be the best next planet to visit to further learn in the world of Python. Instead of making your own functions and exerting yourself how much better would if you could just have the functionality straight away! In the next tutorial, Import, From and As Keywords in Python, I will show you how to do just that. Furthermore, in that guide you will see exhibited just why Python is appraised as a powerhouse goliath in the programming sphere. 


Download the Codes

Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open it up with Python IDLE Shell and run it using the Python Programming Window.

Attachment - Python-Scope-Codes-1-6.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.