How can you share global variables across modules?
How can you share global variables across modules?
To share global variables across modules in Python, you can use several approaches, each with its own advantages and considerations. Here are the primary methods:
One common and effective way to share global variables across different modules is to create a dedicated configuration module, often named config.py
or cfg.py
. This module contains the global variables you want to share.
For example:
# config.py
x = 0
# mod.py
import config
config.x = 1
# main.py
import config
import mod
print(config.x) # Output will be 1
This method is straightforward and maintains consistency across modules by ensuring that all modules refer to the same instance of each variable[1][4].
Similar to the config module approach, you can create a module specifically for global variables. This method centralizes all global variables in one location, making management and updates easier.
Example:
# globals.py
variable1 = 0
# usage in another module
import globals
globals.variable1 = 100
This method is also reflected in various sources as a practical approach to managing global variables ac...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào