Question about object lifetime and access

Asaf Las roegltd at gmail.com
Wed Jan 15 22:50:25 EST 2014


First of all many thanks to all for their detailed answers on subject. 
I really appreciate it!

> 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:
> -- 
> 
> Steven

i have tried some tests, though accessing object from functions increase refcount but only temporary and only if object is used within function. i guess as soon as k is bound to string object latter's reference count will increase and function return results in unbound of k from object (according to output below). 

What is interesting if module namespace can be held accountable for 1 reference count what are remaining 3 references counted on string object referenced by 'p'? (CPython 3.3.2, windows 7, run from within eclipse/PyDev and same output on centos 6.5 for python v3.3.3)

from sys import getrefcount

p = "test script"
print("refcnt before func() ", getrefcount(p))

def access_p1():
    global p
    print("refcnt inside func1()", getrefcount(p))

def access_p2():
    global p
    k = p
    print("refcnt inside func2()", getrefcount(p))

access_p1()
access_p2()

print("refcnt after  func() ", getrefcount(p))

--------------------------------------------------------------
Output:

refcnt before func()  4
refcnt inside func1() 4
refcnt inside func2() 5
refcnt after  func()  4



More information about the Python-list mailing list