Cross-Module Variable in Python
In Python, the __debug__ variable is a convenient global variable available in all modules. However, creating another variable with similar behavior requires a different approach. Here's how to achieve this:
Global Module-Level Variable
If the variable need not be truly global (i.e., updated across modules when modified), a simple module-level variable can suffice.
Example:
a.py:
<code class="python">var = 1</code>
b.py:
<code class="python">import a print(a.var) import c print(a.var)</code>
c.py:
<code class="python">import a a.var = 2</code>
Test:
$ python b.py # Output: 1 2
In this example, the var variable in a.py is accessible to both b.py and c.py. When c.py modifies var, the change is reflected in b.py as well, demonstrating its cross-module behavior.
Real-World Example:
Django, a popular web framework, uses a similar approach with its global_settings.py. Instead of variables, settings are defined as an object (django.conf.settings) that's imported into various Django apps.
The above is the detailed content of How to Achieve Cross-Module Variable Behavior in Python?. For more information, please follow other related articles on the PHP Chinese website!