Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Using Global Variables in Python - Practical Tutorial
Python

Using Global Variables in Python - Practical Tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 6 janvier 2025 · 11 min of reading

In the vast universe of programming, global variables evoke both fascination and caution. Their ability to transcend the boundaries of functions offers undeniable power, but also a potential for chaos if mismanaged. How can you use them effectively without compromising the clarity and robustness of your code? Discover the secrets of global variables, from the magic keyword "global" to managing their mutability, and learn to navigate this delicate balance between utility and complexity.

Using global variables in functions

Global variables in Python are variables declared outside of any function, and they can be accessed in any function defined after their declaration. When working with global variables, it is essential to understand how to manipulate them effectively to avoid potential errors, such as name conflicts or unexpected behaviors.

Declaring and accessing global variables

To use a global variable in a function, simply reference it directly by its name. Let's take a simple example:
python
In this example, the function display_variable accesses the global variable x without any additional declaration.

Modifying global variables

Modifying a global variable inside a function requires using the global keyword. Without this keyword, Python creates a new local variable with the same name, not affecting the global variable. Here’s how to do it:
python
Here, using global y tells Python that we want to use the global variable y and not a new local variable.

Typical use cases

Global variables are often used to store configurations or shared states among different functions in a program. However, their usage should be limited to avoid readability and maintenance issues in the code.

Precautions and best practices

  • Minimize their use: Use global variables sparingly. They can make debugging more difficult since changes can come from any part of the code.
  • Explicit naming: Choose clear and explicit names for your global variables to avoid name conflicts.
  • Document the effects: Clearly indicate in your code where and why a global variable is used or modified.

Alternatives to global variables

In some cases, it may be preferable to use other structures, such as classes or modules, to manage data sharing between functions. This allows for better encapsulation of state and control over data access.
In conclusion, while global variables are a powerful tool, their use must be thoughtful and well-managed to ensure clean and maintainable code.

The global keyword

The global keyword in Python is essential when you want to modify a global variable inside a function. Without this keyword, any assignment to a variable in a function defaults to creating a local variable. Let’s explore how global works and why it is sometimes necessary to use it.

When to use the global keyword

The global keyword is used when you need to modify a global variable inside a function. This is often necessary when managing states that need to be shared and modified by multiple functions in your program. Here’s an illustrative example:
python
In this example, without the global keyword, Python would interpret z as a new local variable, and the value of the global variable z would remain unchanged.

Undesired effects and precautions

Incorrect use of the global keyword can lead to undesirable effects, including maintenance and debugging issues. Here are some precautions to take:
  • Avoid side effects: Limit the use of global to avoid unexpected changes to your global variables. This helps make the code more predictable and less error-prone.
  • Code consistency: Ensure that all modifications made to a global variable are well thought out and documented to prevent potential conflicts or confusion.

Alternatives to using global

In some cases, it may be more appropriate to use classes to encapsulate state and associated behaviors, thus reducing the need for global variables. For example:
python
This approach promotes encapsulation and makes the code more modular and easier to maintain.
In conclusion, while global is a useful tool in certain situations, its use should be carefully controlled to maintain clean and efficient code.

The globals() function

The globals() function in Python is a built-in function that returns a dictionary representing the current global namespace. This tool is particularly useful for inspecting and dynamically manipulating global variables.

Understanding globals()

The globals() function allows access to all global variables defined in the program. The dictionary returned by globals() contains key-value pairs where the keys are the names of the global variables and the values are their corresponding values. Here’s a simple example:
python
In this example, display_globals() will print a dictionary containing entries for a and b, among other global items defined by Python.

Modifying global variables with globals()

While globals() is primarily used for inspection, it can also be used to modify global variables. However, this practice should be used cautiously to avoid unexpected changes. Here’s how it works:
python
In this example, the function modify_a changes the value of a by directly accessing the dictionary returned by globals().

Precautions when using globals()

  • Code clarity: Using globals() to modify variables can make the code harder to read and understand. It is often better to use more explicit methods like the global keyword.
  • Security risks: Directly modifying the global namespace can introduce security risks, especially if unsafe values are injected into the program.

Typical use cases

globals() is often used for inspection and debugging tasks, where understanding the global state of the program is necessary. It can also be used in scripts where dynamic flexibility is required, such as when executing on-the-fly generated code.
In summary, while globals() offers a powerful way to interact with the global namespace, it is recommended to use it cautiously to maintain clear and secure code.

Understanding the effect of mutability on global variables

The mutability of global variables in Python significantly impacts how they can be used and modified across functions. Understanding this characteristic is crucial to avoid unexpected behaviors in your program.

Immutable vs mutable variables

In Python, immutable types include integers, floats, strings, and tuples. When a global variable of these types is modified in a function, a new local variable is often created unless the global keyword is used.
python
In this example, x remains unchanged globally because the modification without global creates a local variable.
Mutable types, such as lists, dictionaries, and sets, can be modified directly without needing the global keyword. This is due to their mutable nature, where operations directly affect the object in memory.
python
Here, the list list is modified directly, illustrating how mutable objects can be changed without global redefinition.

Precautions when using mutable variables

  • Side effects: Be aware of side effects when modifying mutable objects, as these changes apply to all contexts where the object is accessible.
  • State management: Use mutable objects to manage shared states in a program, but document modifications well to avoid confusion.

Best practices

  • Clarity and intent: Always clarify the intent of the modification, especially when it involves mutable objects.
  • Documentation: Document where and why a mutable variable is changed to facilitate code maintenance.
By understanding the effect of mutability on global variables, you can better manage modifications and maintain effective, error-free code.

Creating global variables inside a function

Creating global variables inside a function may seem counterintuitive, but it is possible using the global keyword. This technique can be useful in certain cases, although it should be used with caution to avoid complicating the code.

Using the global keyword

To create a global variable inside a function, you must declare the variable with the global keyword before assigning it. This tells Python that you want to create or modify a variable in the global namespace.
python
In this example, new_variable is created inside define_global_variable but becomes globally accessible after calling the function.

When to use it

Creating global variables in a function can be helpful when the global state needs to be initialized or dynamically updated based on certain conditions or calculations. This can be convenient in scripts where the global state depends on the results of a specific function.

Precautions

  • Readability: This approach can make your code less readable, as global variables are not explicitly defined at the beginning of your program.
  • Name conflicts: Be attentive to potential name conflicts with other global variables. Ensure that variable names are unique and explicit to avoid errors.

Alternatives

If creating global variables inside a function makes the code too complex, consider using structures like classes to encapsulate state. This helps to better organize the code and limit access to variables through specific methods.
python
By choosing an approach that maintains clarity and code maintainability, you can effectively manage global variables in your Python programs.

Deciding when to use global variables

Using global variables in a Python program requires careful consideration to ensure that their use is justified and does not unnecessarily complicate the code. Let’s see when it is appropriate to use global variables and how to manage them effectively.

Advantages of using global variables

Global variables can be useful in several situations:
  • Configuration sharing: When you have parameters or configurations that need to be accessible by multiple functions, global variables can simplify access to this information.
  • Centralized state: For applications where a centralized state needs to be maintained and shared, such as in a video game or simulation application, global variables may be appropriate.

Disadvantages and risks

Despite their advantages, global variables also have disadvantages:
  • Maintenance difficulties: Global variables can make code difficult to maintain because they can be modified anywhere in the program, making tracking changes complex.
  • Name conflicts: Global variables increase the risk of name conflicts, especially in larger projects or with multiple developers.
  • Unpredictability: Uncontrolled changes to global variables can lead to unpredictable behaviors and bugs that are hard to locate.

When to use global variables

To decide if you should use global variables, ask yourself the following questions:
  • Do multiple parts of the program need to access this variable? If so, a global variable might be justified.
  • Does the state of the variable need to be shared and modified by multiple functions? If yes, a global variable might be necessary, but also consider alternative structures like classes.
  • Does using global variables simplify the code without adding unnecessary complexity? If the answer is no, rethink your approach.

Alternatives

When possible, use alternatives like classes to encapsulate state and associated behaviors. This makes your code more modular, easier to understand, and maintain.
In the end, while global variables can be a powerful tool, their use should be well controlled to ensure clean and maintainable code.

Avoiding global variables in your code and functions

While global variables can be useful in certain situations, it is often better to avoid them to maintain clean and maintainable code. Here are some strategies to minimize the use of global variables in your Python programs.

Using function parameters

Instead of relying on global variables, pass the necessary data to your functions as parameters. This improves the readability and modularity of the code.
python
By using parameters, you reduce your functions' dependence on global variables, making them easier to test and reuse.

Encapsulation with classes

Classes are a great alternative for managing shared states without using global variables. They allow you to group related data and functions, facilitating state management.
python
By using classes, you can encapsulate state and behavior, thus reducing exposure to global variables.

Using modules

Python modules allow you to structure your code in a way that avoids global variables. By defining constants or shared states at the module level, you can import them where needed while maintaining a clear separation.
python
This approach allows for centralizing configurations while limiting excessive use of global variables.
By adopting these strategies, you can design more modular and maintainable code while minimizing the risks associated with global variables.

Conclusion

In summary, managing global variables in a Python program requires a thoughtful approach to avoid potential pitfalls such as increased complexity and name conflicts. While global variables offer a powerful way to share information and states between different parts of your code, their use should be limited and well controlled.

Advantages and disadvantages

Global variables can simplify access to shared configurations, but they can also make code difficult to maintain and debug. Undesired side effects, due to unforeseen modifications, are common risks associated with their use.

Best practices

Prioritize using function parameters, encapsulation with classes, and structuring code with modules to minimize global dependencies. These practices encourage better code organization and facilitate long-term maintenance.

Informed choice

Ultimately, the choice to use or not use global variables should be guided by considerations of code readability, modularity, and maintainability. By adopting a cautious approach and using appropriate alternatives, you can optimize the structure of your program, ensuring effective and error-free development.

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee
Image de la formation Become a Data Engineer
Become a Data Engineer
9 months
Advanced
Guarantee

Associated articles

See all our articles