Back to Python
2026-01-276 min read

Global Attributes (Python Programming)

Learn Global Attributes (Python Programming) step by step with clear examples and exercises.

Title: Global Attributes in Python Programming

Why This Matters

Understanding and effectively utilizing global attributes is crucial for writing efficient, scalable, and maintainable code, especially when working on larger projects. Global attributes help you avoid naming conflicts, make your code more modular, and improve its overall organization. By managing variables across functions with global attributes, you can create more reusable code that is easier to understand and debug.

Prerequisites

Before diving into global attributes, you should be familiar with the following concepts:

  1. Basic Python syntax (variables, data types, operators)
  2. Functions and function definitions
  3. Scope of variables in Python (local, global, and built-in)
  4. The global keyword
  5. Understanding how to create and manipulate lists and dictionaries
  6. Basic file handling using the built-in open() function
  7. Basic conditional statements (if, elif, else)
  8. Understanding the concept of modules and imports

Core Concept

Global attributes refer to variables that are defined outside any function or inside a function but without the global keyword. These variables have global scope, meaning they can be accessed from anywhere in your code, including other functions. Global attributes allow you to share data between functions and make your code more modular and reusable.

To demonstrate, let's create a simple example:

Define a global variable

my_global = 10

def test():

Access and modify the global variable

print("Inside function: my_global is", my_global)

my_global = 20

test()

print("Outside function: my_global is", my_global)

Output:

Inside function: my_global is 10

Outside function: my_global is 20

In this example, `my_global` is a global variable because it's defined outside the function. When we call the `test()` function, we can access and modify the global variable. The changes made to the global variable inside the function persist even after the function has finished executing.

### Global Keyword

The `global` keyword is used to explicitly declare that a variable inside a function should have global scope instead of local scope. This allows you to avoid naming conflicts between local and global variables with the same name:

Define a global variable

my_global = 10

def test():

Declare my_local as a local variable

my_local = 20

print("Inside function: my_local is", my_local)

Access and modify the global variable using the global keyword

global my_global

my_global += 10

test()

print("Outside function: my_global is", my_global)

Output:

Inside function: my_local is 20

Outside function: my_global is 20

In this example, we first define a global variable `my_global`. Inside the `test()` function, we declare `my_local` as a local variable. To modify the global `my_global`, we use the `global` keyword to explicitly declare it as global. This allows us to access and modify the global variable without affecting the local one.

Worked Example

Let's create a simple program that uses global variables to manage user preferences:

Define some default user preferences

name = "John Doe"

theme = "light"

def save_preferences():

with open("user_prefs.txt", "w") as f:

f.write(f"Name: {name}\nTheme: {theme}")

def load_preferences():

with open("user_prefs.txt", "r") as f:

data = f.readlines()

name, theme = data[0].strip().split(": ")

return name, theme

Save user preferences when the program starts

save_preferences()

name, theme = load_preferences()

print(f"Welcome back, {name}! Your current theme is {theme}.")

def change_theme():

global theme

if theme == "light":

theme = "dark"

else:

theme = "light"

Change the user's theme and save the new preferences

change_theme()

save_preferences()

print(f"Your theme has been changed to {theme}.")


### User Preference Functions

In this example, we define two functions: `save_preferences()` and `load_preferences()`. These functions use global variables to manage user preferences by writing and reading data from a file called "user_prefs.txt". The `change_theme()` function modifies the global `theme` variable and saves the new preference using the `save_preferences()` function.

Common Mistakes

  1. Forgetting to use the global keyword when modifying a global variable inside a function:
my_global = 10

def test():
my_global = 20 # This overrides the global variable
print("Inside function: my_global is", my_global)

test()
print("Outside function: my_global is", my_global)

Output:

Inside function: my_global is 20
Outside function: my_global is 10

To fix this, use the global keyword to explicitly declare that you want to modify the global variable.

  1. Using a local variable with the same name as a global variable and not using the global keyword:
my_global = 10

def test():
my_global = 20 # This creates a new local variable, hiding the global one
print("Inside function: my_global is", my_global)

test()
print("Outside function: my_global is", my_global)

Output:

Inside function: my_global is 20
Outside function: my_global is 10

To fix this, use the global keyword to access and modify the global variable.

  1. Modifying a global variable inside a function without using the global keyword, but forgetting to assign the new value back to the global variable:
my_global = 10

def test():
my_global += 10 # This modifies the global variable, but we don't assign the new value back
print("Inside function: my_global is", my_global)

test()
print("Outside function: my_global is", my_global)

Output:

Inside function: my_global is 20
Outside function: my_global is 10

To fix this, use the global keyword and assign the new value back to the global variable.

Practice Questions

  1. Write a program that defines a global variable my_number, initializes it to 5, and then defines two functions: increment() and decrement(). Use the global keyword to allow these functions to modify the value of my_number.
  1. Write a program that defines a global variable my_list containing the numbers 1, 2, 3, and 4. Define two functions: add_one() and multiply_by_two(). Use the global keyword to allow these functions to modify the values in my_list.
  1. Write a program that defines a global variable my_dictionary with keys "name" and "age". Define two functions: change_name() and increment_age(). Use the global keyword to allow these functions to modify the values in my_dictionary.
  1. Write a program that defines a global variable my_list containing the numbers 1, 2, 3, and 4. Define a function reverse_list() that reverses the order of the numbers in my_list. Use the global keyword to allow this function to modify the values in my_list.

FAQ

What happens if I don't use the global keyword when modifying a global variable inside a function?

Answer: If you forget to use the global keyword, Python creates a new local variable with the same name, hiding the global one. To modify the global variable, you must explicitly declare it as global using the global keyword.

Can I access and modify a global variable without using the global keyword?

Answer: Yes, you can access a global variable without using the global keyword because they are accessible from anywhere in your code. However, if you want to modify a global variable inside a function, you must use the global keyword to explicitly declare it as global.

What is the difference between local and global variables?

Answer: Local variables are defined within a function and can only be accessed from that function or nested functions. Global variables are defined outside any function and can be accessed from anywhere in your code.

Can I have multiple global variables with the same name in different modules?

Answer: Yes, you can have multiple global variables with the same name in different modules, but it may lead to naming conflicts if those variables are imported or used together. To avoid this, use meaningful variable names or explicitly declare which variable you want to modify using the global keyword.

Is it a good practice to use global variables?

Answer: While global variables can make your code more modular and reusable, they can also lead to unintended side effects and make your code harder to understand and debug. It's generally recommended to minimize the use of global variables and instead pass data between functions using function arguments or return values when possible.

Global Attributes (Python Programming) | Python | XQA Learn