简体   繁体   中英

Python class variable usage across thread have different value

I'm getting confused about class variable access through multi-thread. I'm in a django application and I initialize a class at server startups to inject some configuration. Then on user requests I call some method on that class but the config is 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"

if usefull in the django settings class loaded at startup I do:

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!)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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