如何在Python中跨脚本添加全局可访问变量并实现同步更新?
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

