How do I create or use a global variable inside a function?
How do I use a global variable that was defined in one function inside other functions in Python?
Absolutely! Here are some other common techniques for working with variables that need to be shared across functions in Python, offering alternatives to global variables:
1. Nested Functions
def outer_function(value):
def inner_function():
print("Value from outer function:", value)
inner_function()
outer_function(10) # Output: Value from outer function: 10
2. Modules
# my_module.py
shared_data = "This is accessible from other files"
def my_module_function():
print(shared_data)
# main.py
import my_module
my_module.my_module_function() # Accessing data from the module
3. Classes
class DataHolder:
def __init__(self, initial_data):
self.data = initial_data
def get_data(self):
return self.data
def update_data(self, new_data):
self.data = new_data
data_store = DataHolder("Some data")
print(data_store.get_data())
Choosing the Right Technique
The best method depends on the complexity of your project and the nature of the shared data:
Here's a breakdown of global variables in Python, along with best practices and examples:
How to use global variables in functions
my_global_var = 10
def my_function():
print(my_global_var) # Accessing the global variable
my_function() # Output: 10
global
keyword.my_global_var = 10
def my_function():
global my_global_var
my_global_var = 20 # Modifying the global variable
my_function()
print(my_global_var) # Output: 20
Creating a global variable inside a function
You can create a global variable inside a function using the global
keyword:
def my_function():
global new_global_var
new_global_var = "Hello"
my_function()
print(new_global_var) # Output: Hello
Why you should generally avoid global variables
While global variables seem convenient, they are generally discouraged for the following reasons:
Best Practices
Example: Refactoring with arguments
def calculate_area(length, width): # Explicit arguments
area = length * width
return area
result = calculate_area(5, 10)
print("The area is:", result)
1