在文件之间使用全局变量?

2024-04-19 05:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我对全局变量的工作方式有点困惑。我有一个大项目,大约有50个文件,我需要为所有这些文件定义全局变量。

我所做的是在我的项目main.py文件中定义它们,如下所示:

# ../myproject/main.py

# Define global myList
global myList
myList = []

# Imports
import subfile

# Do something
subfile.stuff()
print(myList[0])

我试图在subfile.py中使用myList,如下所示

# ../myproject/subfile.py

# Save "hey" into myList
def stuff():
    globals()["myList"].append("hey")

我尝试了另一种方法,但也没有成功

# ../myproject/main.py

# Import globfile    
import globfile

# Save myList into globfile
globfile.myList = []

# Import subfile
import subfile

# Do something
subfile.stuff()
print(globfile.myList[0])

subfile.py里面我有这个:

# ../myproject/subfile.py

# Import globfile
import globfile

# Save "hey" into myList
def stuff():
    globfile.myList.append("hey")

但还是没用。我应该如何实现这一点?我知道,当两个文件并不真正了解对方(well subfile不知道main)时,它不能像这样工作,但我想不出如何做到这一点,而不使用io写或pickle,这是我不想做的。


Tags: 文件项目pyimportmainsavemyprojecthey
3条回答

请参阅Python关于sharing global variables across modules的文档:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

config.py:

x = 0   # Default value of the 'x' configuration setting

Import the config module in all modules of your application; the module then becomes available as a global name.

main.py:

import config
print(config.x)

or

from config import x
print(x)

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

问题是您从main.py定义了myList,但是subfile.py需要使用它。这里有一个解决这个问题的干净方法:将所有全局变量移到一个文件中,我称这个文件为settings.py。此文件负责定义全局参数并初始化它们:

# settings.py

def init():
    global myList
    myList = []

接下来,您的subfile可以导入全局变量:

# subfile.py

import settings

def stuff():
    settings.myList.append('hey')

注意subfile不调用init()-该任务属于main.py

# main.py

import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result

这样,可以在避免多次初始化全局变量的同时实现目标。

您可以将Python全局变量看作“模块”变量,因此它们比C语言中传统的“全局变量”要有用得多

全局变量实际上是在模块的__dict__中定义的,可以作为模块属性从该模块外部访问。

所以,在你的例子中:

# ../myproject/main.py

# Define global myList
# global myList  - there is no "global" declaration at module level. Just inside
# function and methods
myList = []

# Imports
import subfile

# Do something
subfile.stuff()
print(myList[0])

以及:

# ../myproject/subfile.py

# Save "hey" into myList
def stuff():
     # You have to make the module main available for the 
     # code here.
     # Placing the import inside the function body will
     # usually avoid import cycles - 
     # unless you happen to call this function from 
     # either main or subfile's body (i.e. not from inside a function or method)
     import main
     main.mylist.append("hey")

相关问题 更多 >