Global Variables in Python

Course: Global Variables in Python

Introduction

In Python, variables can have different scopes, meaning the sections of code where they are accessible. A global variable is defined at the module level (i.e., outside of any function or class) and is accessible from any point in the module after its definition. However, functions and methods can also create their own local variables, which are only accessible within those functions. This can sometimes lead to conflicts or errors if you try to modify a global variable from within a function without using it correctly.

Global Variables

Definition and Scope

Definition

A global variable is a variable that is defined at the module level, outside of any function or class. It is accessible from any place within the module after its declaration.

Scope

The scope of a global variable is the entire file (module) in which it is defined. This means a global variable is accessible from all functions and classes defined after its declaration. However, it is not directly accessible from imported modules unless explicitly exposed.

Basic Example of a Global Variable

Here’s a simple example to illustrate how a global variable works:

# Defining a global variable
number = 42
def display_number():
    print("Number in display_number():", number)
def modify_number(new_number):
    global number  # Indicates that we are referring to the global variable 'number'
    number = new_number
display_number()  # Outputs 42
modify_number(100)
display_number()  # Outputs 100

Explanation

  • Definition: number is a global variable defined at the module level.
  • Access: display_number() accesses number directly without needing to declare it as global.
  • Modification: modify_number() uses the global keyword to modify the global variable number. Without global, a new local variable number would be created inside the function.

Global Variables in Modules

Global variables can also be defined in one module and used in other modules through imports. Here’s an example:

config.py (module containing global variables) 

# Global variables
URL_API = "https://api.example.com"
TIMEOUT = 30

 main.py (module using global variables) 

import config
def make_request():
    url = config.URL_API
    timeout = config.TIMEOUT
    print(f"Making a request to {url} with a timeout of {timeout} seconds.")
make_request()

Explanation

  • Variables URL_API and TIMEOUT are defined in config.py and are accessible in main.py via the import of the config module.
  • This shows how global variables can be shared between different files/modules.

Considerations and Best Practices

Managing Global Variables

Excessive use of global variables can make code harder to understand and maintain. Here are some best practices for managing global variables:

  • Encapsulation: Use classes to encapsulate global variables, which helps in better organizing the code and controlling access to these variables.
  • Minimization: Limit the number of global variables and prefer passing variables as function parameters or using local variables when possible.
  • Clarity: Clearly document global variables and their usage to avoid confusion and errors.

Example of Encapsulation with a Class 

class Configuration:
    def __init__(self):
        self.url_api = "https://api.example.com"
        self.timeout = 30
config = Configuration()
def make_request():
    url = config.url_api
    timeout = config.timeout
    print(f"Making a request to {url} with a timeout of {timeout} seconds.")
make_request()

 Explanation

  • Here, Configuration encapsulates url_api and timeout as instance attributes.
  • This allows for creating different objects with different configurations if needed and makes the code more modular and understandable.

Conclusion

Global variables are a powerful tool for sharing data across different parts of a module, but they should be used with caution. By understanding their scope and applying best practices, you can avoid common pitfalls and write cleaner, more maintainable code.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *