What's the lifetime of a class attribute, in Python? If no instances of the class are currently live, might the class and its class attributes be garbage-collected, and then created anew when the class is next used?
For example, consider something like:
class C(object):
l = []
def append(self, x):
l.append(x)
Suppose I create an instance of C
, append 5 to C.l
, and then that instance of C
is no longer referenced and can be garbage-collected. Later, I create another instance of C
and read the value of C.l
. Am I guaranteed C.l
will hold [5]
? Or is it possible that the class itself and its class attributes might get garbage-collected, and then C.l = []
executed a second time later?
Or, to put it another way: Is the lifetime of a class attribute "forever"? Does a class attribute have the same lifetime as a global variable?