sys.getrefcount return non continuous value for different scope

Viewed 57

I want to know how the memory allocated in python.For that,I used to playing on python.But I got stuck on below issue.

For the below code, If I use 10 instead of 1000 I got expected reference count value within the function

import sys
def show_ref_count(a):
    print("ref count of 1000 within function : ",sys.getrefcount(1000))
    print("adrs of a : ",id(a))

# main function
a = 1000
b = 1000
c = 1000
print("ref count of 1000 : ",sys.getrefcount(1000))
print("adrs of a : ",id(a))
show_ref_count(a)

And the output for the code is

ref count of 1000 :  6
adrs of a :  140309334530448
ref count of 1000 within function :  3
adrs of a :  140309334530448

Integer 1000 stored in Memory loc : 140309334530448 and same address used by both main and show_ref_count. But in show_ref_count function, reference count for 1000 is showing as 3 not 7.Why?

1 Answers

Because 1000 initialized inside main and 1000 inside show_ref_count are not the same objects. You can add one line to your function

import sys
def show_ref_count(a):
    print("ref count of 1000 within a function: ", sys.getrefcount(1000))
    print("addr of var: ", id(a))
    print("addr of 1000 within function: ", id(1000))

# main function
a = 1000
b = 1000
c = 1000

print("ref count of 1000: ", sys.getrefcount(1000))
print("addr of a: ", id(a))
print("addr of 1000: ", id(1000))

show_ref_count(a)

and check the output

ref count of 1000:  3
addr of a:  140646358917616
addr of 1000:  140646358918000

ref count of 1000 within a function:  2
addr of var:  140646358917616
addr of 1000 within function:  140646390098512

to figure out that these two 1000's are actually different objects, so the number of refs is also different.

Note: also a being initialized with 1000 is not the same object, and also has a different address (if you take a look on the output above). It happens since variables in Python are not actually variables but rather 'names' of objects. From the article an overall process looks as follows:

  1. Create a PyObject

  2. Set the typecode to integer for the PyObject

  3. Set the value to 1000 for the PyObject

  4. Create a name called a

  5. Point a to the new PyObject

  6. Increase the refcount of the PyObject by 1

Related