Python class 跨线程的变量使用有不同的值

Python class variable usage across thread have different value

我对通过多线程进行的 class 变量访问感到困惑。我在 Django 应用程序中,我在服务器启动时初始化 class 以注入一些配置。然后根据用户请求,我在 class 上调用了一些方法,但配置是 None.

class SharedService:
    _queue_name = None

    @staticmethod
    def config(queue_name=None):
        if queue_name:
            SharedService._queue_name = queue_name
        print(SharedService._queue_name)    # this print the "alert"

    @staticmethod
    def send_message(data):
        print(SharedService._queue_name)    # this print None should print "alert"

如果在 django 设置中有用 class 在启动时加载我这样做:

SharedService.config(queue_name="alert")

并且在用户端点我只是调用:

SharedService.send_message("blabla")

我确定它以前确实有效,但我们最近确实更新了 python 3.10 和 django 3.2,并且可能相关(或不相关!)

好的,那完全是外场!

共享服务来自外部库,由于我们的python路径错误,实际上可以从两个路径导入。

在设置文件中,我在做

from lib.services import SharedService

以及请求处理代码

from services import SharedService

这显然创建了两个不同的 class 定义,因此,第二个用法未初始化。