Global Variable

A global variable in Python is a variable that is declared outside of any function or class, making it accessible throughout the entire module. This allows for the sharing of data across different functions within the same module. However, modifying a global variable within a function requires the use of the global keyword to ensure that the function refers to the global variable rather than creating a new local one.

Overview

A global variable is defined in the global scope and can be accessed by any function or class within the same module. This means that once a global variable is declared, it can be used throughout the module. However, if you need to change the value of a global variable within a local scope, such as inside a function, you must use the global keyword. This keyword tells Python that the variable is defined in the global scope and should not be treated as a new local variable.

Example of Global Variable Usage

Consider the following example, which demonstrates the use of global variables:

def fun():
    global a
    a = 1
    b = 2

In this example, the function fun treats a as a global variable and b as a local variable. The global keyword is used to declare a as a global variable, allowing the function to modify the global a. The variable b, however, is local to the function and cannot be accessed outside of it.

Understanding Global Variables with Examples

Attempting to Change a Global Variable

Consider the following example, which demonstrates an attempt to change a global variable without using the global keyword:

db_filename = "N/A"

def set_database(db_name):
   db_filename = db_name

set_database("tasks.sqlite")

print(db_filename)
# [Output: "N/A"](https://livebook.manning.com/book/python-how-to/chapter-10/190)

In this example, db_filename is a global variable intended to store the file path of a database. The function set_database attempts to assign a new value to db_filename, but without the global keyword, it creates a new local variable instead, leaving the global db_filename unchanged.

Successfully Changing a Global Variable

To successfully change the value of a global variable from within a function, you must declare the variable as global using the global keyword:

db_filename = "N/A"

def set_database(db_name):
   global db_filename
   db_filename = db_name

set_database("tasks.sqlite")

print(db_filename)
# [Output: tasks.sqlite](https://livebook.manning.com/book/python-how-to/chapter-10/190)

In this corrected version, the global keyword is used inside the set_database function to indicate that db_filename refers to the global variable. This prevents the creation of a new local variable and allows the function to modify the global db_filename.

Global and Nonlocal Keywords

The global keyword is used to declare a variable as global, allowing it to be accessed and modified by functions that declare it as such. Similarly, the nonlocal keyword is used to refer to a variable in the closest enclosing scope that is not global. This is particularly useful in nested functions where you want to modify a variable in an outer, but not global, scope.

Example of Global and Nonlocal Keywords: File nonlocal.py](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-9/91)

g_var = 0
nl_var = 0

def test():
    nl_var = 2
    def inner_test():
        global g_var
        nonlocal nl_var
        g_var = 1
        nl_var = 4

    inner_test()

test()

In this example, g_var is declared as a global variable, allowing it to be modified within the inner_test function. The nonlocal keyword is used for nl_var, allowing inner_test to modify nl_var in the test function, which is the closest enclosing scope.

Usage and Best Practices

While the use of global variables is common in programming, it is generally not considered a best practice. Global variables can lead to code that is difficult to understand and maintain, as they can be modified from anywhere in the program, leading to unexpected behaviors and bugs that are hard to trace. Therefore, it is advisable to avoid using global variables unless absolutely necessary. Instead, consider using function parameters and return values to pass data between different parts of your program. This approach promotes better encapsulation and modularity, making your code more robust and easier to manage.

Namespaces

Python maintains separate namespaces for local and global variables. The locals() function returns a dictionary of the current local symbol table, while globals() returns a dictionary of the current global symbol table. These namespaces can be the same in certain contexts, such as interactive sessions.

Example of Namespaces

locals()

globals()

In this example, the local and global namespaces are initially the same, containing entries for internal use such as __name__, __doc__, and __builtins__.

Adding Variables to Namespaces

z = 2
import math
from cmath import cos

globals()

locals()

After creating a variable z and importing modules, the local and global namespaces are updated to include these new bindings. The math module and the cos function from the cmath module are added to both namespaces, demonstrating their equivalence in this context.

For more detailed information, you can refer to the The Quick Python Book, Fourth Edition, Python How-To, and Tiny Python Projects.

| Book Title | Usage of Global Variable | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|--------------------------|-----------------|-------------------------------|---------------|-----------------------|
| [The Quick Python Book, Fourth Edition](https://www.manning.com/books/the-quick-python-book-fourth-edition) | Discusses global variables as a means to share data across functions within the same module. | Explains the use of `global` and `nonlocal` keywords, and how they interact with namespaces. | Connects to concepts like namespaces and the `nonlocal` keyword. | Provides code examples demonstrating global and nonlocal variable usage. | Highlights practical scenarios where global variables are used, such as modifying variables in nested functions. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-9/86) |
| [Python How-To](https://www.manning.com/books/python-how-to) | Describes global variables as accessible throughout the module and emphasizes the need for the `global` keyword to modify them within functions. | Focuses on the necessity of the `global` keyword for modifying global variables in local scopes. | Discusses the implications of not using the `global` keyword when modifying global variables. | Includes examples showing both unsuccessful and successful attempts to modify global variables. | Demonstrates practical use in a task management app scenario. [more](https://livebook.manning.com/book/python-how-to/chapter-10/207) |
| [Tiny Python Projects: Learn coding and testing with puzzles and games](https://www.manning.com/books/tiny-python-projects) | Defines global variables as accessible throughout the program but advises against their use. | Discusses the drawbacks of using global variables, such as difficulty in understanding and maintaining code. | Encourages using function parameters and return values instead of global variables for better encapsulation. | Does not provide specific examples but discusses best practices. | Suggests avoiding global variables to promote code modularity and robustness. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-22/129) |

FAQ (Frequently asked questions)

How can you change a global variable within a local scope in Python?