You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中跨脚本添加全局可访问变量并实现同步更新?

How to Add Shared Variables Across Python Scripts (Global/Single-Point Access)

Got it, let's tackle this problem step by step. The key here is understanding that Python modules are loaded as singleton objects—meaning once you import a module anywhere in your code, it's the same instance everywhere. We can use this to add and sync variables between scripts without extra complexity.

Step 1: Update file1.py with an add function

First, we'll modify file1.py to include an add function that adds the surname variable directly to the module's namespace. This way, any changes will be reflected in the shared module instance.

# file1.py
v = 10
name = "lko"

def add(surname):
    # Add the surname as a module-level variable
    globals()['surname'] = surname

Step 2: Use file1.py in file2.py

Now in file2.py, we can import file1, access its initial variables, and call the add function to set the new surname variable. Since the module is a singleton, this new variable will be available in file1's namespace immediately.

# file2.py
import file1

# Print the initial variable from file1
print(file1.v)  # Output: 10

# Call the add function to set the surname
file1.add(surname="dhg")

# Now we can access the new variable directly from file1
print(file1.surname)  # Output: dhg

Why this works

When you import file1 in file2, Python loads the module once and stores it in sys.modules. Any changes you make to the module's attributes (like adding the surname variable via the add function) are applied to this single shared instance. So if you import file1 in another script later, it will already have the surname variable set to "dhg".

Quick clarification

Note that this adds the surname variable to the runtime instance of file1.py, not the actual source code file on your disk. If you need to permanently edit the file1.py file to include surname="dhg", you'd need to write code to modify the file's content (using file I/O operations). But for most use cases where you need shared variables during program execution, the singleton module approach is the cleanest solution.

内容的提问来源于stack exchange,提问作者Deepak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:43:12