Home > Backend Development > Python Tutorial > How Can I Share Global Variables Between Python Files Without Using `pickle` or `io`?

How Can I Share Global Variables Between Python Files Without Using `pickle` or `io`?

Barbara Streisand
Release: 2024-12-25 19:03:10
Original
158 people have browsed it

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
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template