Question about object lifetime and access
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Jan 15 19:02:42 EST 2014
On Wed, 15 Jan 2014 05:14:59 -0800, Asaf Las wrote:
> I have read somewhere that global objects are referenced from module
> namespace will never have reference count down to 0 even if they are not
> referenced from functions or class methods. Is this true?
Correct. The global name is a reference, so the reference count will be
at least 1. In fact, referencing the name from a function or method
doesn't increase the ref count:
instance = 123.456789 # ref count of float is 1
def test():
print(instance) # This refers to the *name* "instance", not the float
So the test() function cannot keep the float alive. If you reassign
global instance, test() will see the new value, not the old, and
123.456789 is free to be garbage collected.
This sounds more complicated than it actually is. In practice it works
exactly as you expect global variables to work:
py> test()
123.456789
py> instance = 98765.4321
py> test()
98765.4321
> Does it mean
> that global objects are destroyed when interpreter exits or thread where
> it runs is terminated?
Certainly not! Global objects are no different from any other object.
They are destroyed when their reference count falls to zero. In the case
of global objects, that is *often* not until the interpreter exits, but
it can be before hand.
So long as the object is in use, it will be kept. When it is no longer in
use, the garbage collector is free to destroy it. So long as *some*
object or name holds a reference to it, it is considered to be in use.
value = instance = 1.23456 # ref count 2
alist = [1, 2, 3, 4, 5, value] # ref count now 3
mydict = {"Key": alist} # ref count now 4
value = 42 # rebind a name, ref count of float now 3
mydict.clear() # ref count now 2
del instance # delete the name, ref count now 1
assert alist[5] == 1.23456
alist[5] = 0 # final reference gone, ref count is now 0
At this point the global object 1.23456 is free to be destroyed.
(Note: some Python implementations don't do reference counting, e.g.
Jython and IronPython use the Java and .Net garbage collectors
respectively. In their case, the same rule applies: where there are no
longer any references to an object, it will be garbage collected. The
only difference is in how soon that occurs: in CPython, it will be
immediate, in Jython or IronPython it will occur when the garbage
collector runs.)
--
Steven
More information about the Python-list
mailing list