Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django python - are class attributes values shared between requests?

Tags:

python

oop

django

Let's say I have the following class in Python:

class MyClass():
    cls_att = []

Now, in one of the requests I'm doing the following:

MyClass.cls_att.append('a')

If immediately after this 'append', another request will get the attribute:

lst = MyClass.cls_att

What they will get in 'lst'? is it empty list or ['a']?

like image 875
user2880391 Avatar asked Dec 05 '25 22:12

user2880391


1 Answers

It depends.

Any requests that are served by the same process will use the same class, so will see the added data. Requests that are served by a different process will see any data added by previous requests on that process.

So, since you can't predict what process will serve any particular request, you can't count on this either happening or not happening. In other words, don't do this at all.

like image 70
Daniel Roseman Avatar answered Dec 08 '25 11:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!