Python Scope
About Python Scope
In Python, the scope determines the visibility and accessibility of variables in different parts of code. Understanding scope is very crucial for writing clean, efficient, and bug-free Python programs.
Python has four main types of scope, often summarized by the LEGB rule:
- Local (L): Variables defined within a function. They are accessible only within that function.
- Enclosing (E): Variables in the local scope of enclosing functions. This is relevant for nested functions.
- Global (G): Variables defined at the top level of a script or module or explicitly declared as global. They are accessible throughout the module.
- Built-in (B): Names pre-assigned in the built-in names module. These are always available in any Python code.
Local Scope of Variables
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
The local scope of a variable is created when the function is called, and lasts until the function returns.
The local variable cannot be accessed from outside the function.
The following example demonstrates a variable with a local scope:
Example of Local Variables
Calling variable outside the function will raise an error
Explanation of the above example:
- In the above example, the variable
'num'is defined inside the function'my_function()', making it a local variable. - When we call
'my_function()', it prints the value of'num'as 10. - If we try to access
'num'variable from outside the function, it will raise a'NameError'exception because'num'is not defined in the global scope. -
print(num)will raise an error:NameError: name 'num' is not defined'because'num'is not defined outside the function.
Enclosing Scope of Variables
The enclosing scope comes into play when there are functions defined inside other functions.
A variable defined in the local scope of an enclosing function is accessible to the nested functions within that enclosing function.
If a variable is not found in the local scope of the inner function, Python then searches the enclosing scope (the local scope of the outer function).
The following example demonstrates a variable with an enclosing scope:
Example of Enclosing Scope of Variables
Explanation of the above example:
- In the above example, the variable
'message'is defined in the local scope of the'outer_function()', making it accessible to the nested'inner_function()'. - When
inner_functionis executed, it first looks for the variable'message'in its own local scope. It doesn't find it there. - Then it looks in the enclosing scope, which is the local scope of
'outer_function()'. - It finds
'message'there and prints its value:"Hello from the outer function!".
Example of Modifying Enclosing Scope Variable Using nonlocal Keyword
Explanation of the above example:
- In the above example, the variable
'count'is defined in the local scope of the'outer_function()', making it accessible to the nested'inner_function()'. - The
'nonlocal'keyword is used inside'inner_function()'to indicate that we want to modify the variable'count'from the enclosing scope (the local scope of'outer_function()'). - Each time we call
'output()', it increments the value of'count'by 2 and prints the modified value. - This demonstrates how a nested function can access and modify a variable from its enclosing scope using the
'nonlocal'keyword.
Global Scope of Variables
Global Variables are those defined in the main body of a Python file (at the module level), outside of any function or class definition.
A global variable can be accessed from any function or class within the same module.
A global variable can be read from within a function, but cannot be modified.
To modify a global variable inside a function, you must use the 'global' keyword to declare the variable as global within the function's scope.
A global variable can be declared inside a function using the 'global' keyword, which allows you to modify the variable outside of its local scope.
The following example demonstrates a variable with a global scope:
Example of Global Variables
Explanation of the above example:
- In the above example, the variable
'global_message'is defined outside of any function, making it a global variable. - The function
'accessing_global()'accesses (reads) the global variable'global_message'and prints its value. - When we call
'accessing_global()', it successfully prints the value of the global variable.
Example of Local Variable Shadowing Global Variable
Explanation of the above example:
-
In the above example, there is a global variable
'count'defined with a value of 10. -
Inside the function
'local_shadowing()', we define a local variable with the same name'count'and assign it a value of 5. This local variable shadows the global variable within the scope of the function. -
When we call
'local_shadowing()', it prints the value of the local variable, which is 5. -
After the function call, when we print the value of
'count'outside the function, it still holds the value of 10, demonstrating that the global variable was not modified by the local variable inside the function.
Example of Modifying Global Variable Inside a Function
Explanation of the above example:
-
In the above example, the variable
'count'is defined outside of any function, making it a global variable. -
The function
'modify_global()'uses the'global'keyword to indicate that it intends to modify the global variable'count'. -
When we call
'modify_global()', it increments the value of the global variable by 1 and prints the updated value. -
After the function call, when we print the value of
'count'outside the function, it reflects the modified value, which is now 11.
Python's Built-in Scope of Variables and Functions
Python's Built-in Scope contains all the predefined names that are available to any Python program.
These names are part of the built-in namespace and include functions, exceptions, and other objects that are always available in Python without needing to import any modules.
Examples of built-in names include 'print()', 'len()', 'int()', 'str()', 'list()', 'dict()', 'sum()', and many more.
You can view all the built-in names in Python by using the 'print(dir(__builtins__))' command, which lists all the names defined in the built-in namespace.
Example of Accessing Built-in Names
Explanation of the above example:
-
In the above example, we define a function
'calculate_total()'that takes a list as an argument and returns the sum of its elements using the built-in'sum()'function. -
We create a list
'x'containing the numbers 1, 2, and 3. -
We call the function
'calculate_total(x)'to compute the total of the list, which is 6. -
Finally, we use the built-in
'print()'function to display the result. -
This example demonstrates how built-in names like
'sum()'and'print()'can be used directly in Python code without any additional imports or definitions.
Python Compiler For Live Practice
Practice the above Python code in the following Python Editor. Create more Python variables in different scopes in the following code editor and click Execute button. Output will be displayed in Python Code Output section.
Python Editor