简体   繁体   English

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

[英]Python class variable usage across thread have different value

I'm getting confused about class variable access through multi-thread.我对通过多线程访问 class 变量感到困惑。 I'm in a django application and I initialize a class at server startups to inject some configuration.我在一个 django 应用程序中,我在服务器启动时初始化一个 class 以注入一些配置。 Then on user requests I call some method on that class but the config is None.然后根据用户请求,我在该 class 上调用了一些方法,但配置为无。

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"

if usefull in the django settings class loaded at startup I do:如果在启动时加载的 django 设置 class 有用,我会这样做:

SharedService.config(queue_name="alert")

and in the user endpoint I just call:在我刚刚调用的用户端点中:

SharedService.send_message("blabla")

I'm sure it did work previously, but we did update to python 3.10 and django 3.2 recently and might be related (or not!)我确定它以前确实有效,但我们最近确实更新到 python 3.10 和 django 3.2 并且可能相关(或不相关!)

Ok that was completely from outer field!好的,这完全来自外场!

The shared service is from an external library and can actually be imported from two paths because of errors in our python path.共享服务来自外部库,实际上可以从两个路径导入,因为我们的 python 路径中存在错误。

In the settings file, I was doing在设置文件中,我正在做

from lib.services import SharedService

And from the request handling code并从请求处理代码

from services import SharedService

Which obviously creates two different class definitions and thus, the second usage isn't initialized.这显然创建了两个不同的 class 定义,因此,第二个用法没有初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM