Home >Backend Development >Python Tutorial >How Can I Share Global Variables Between Python Files Without Using `pickle` or `io`?
Using Global Variables Between Files Without pickle or io Writing
Global variables provide a convenient mechanism to share data across multiple parts of a program. However, accessing global variables defined in one file from another file can be challenging.
Consider the following scenario: You have a project with multiple files, and you want to define global variables that can be accessed by all of them.
Method 1: Indirect Access
The difficulty with using global variables across files lies in module isolation. Modules in Python are executed independently, so defining a global variable in one module does not automatically make it available to other modules.
To resolve this, consider defining the global variables in a separate file, such as settings.py. This file will be responsible for initializing and providing access to the global variables.
# settings.py def init(): global myList myList = [] # main.py import settings settings.init() # Initialize the global variables import subfile # Import the subfile that needs access to the globals # subfile.py import settings def stuff(): settings.myList.append("hey") # Access the global variable
Method 2: Direct Access
Another method is to use a module attribute to declare the global variables. This essentially exposes the variables as attributes of the module.
# settings.py myList = [] # main.py import settings import subfile # subfile.py import settings def stuff(): settings.myList.append("hey")
Both methods allow you to access global variables across multiple files, ensuring data consistency throughout your program.
The above is the detailed content of How Can I Share Global Variables Between Python Files Without Using `pickle` or `io`?. For more information, please follow other related articles on the PHP Chinese website!