Quick actions

cmd+k|ctrl+k

Navigation

Languages

3. reference_count

Snippet info

Language

Python

Visibility

public

Author

aaron.lung.wai

Created

2022-11-14T12:10:55.650432Z

Updated

2026-06-23T08:55:53.477753Z

import sys
a = [1,2,3]
print(f"a address is {hex(id(a))}") 
'''# a is passing into a function, so a counter become 2,
can't use normal python to check
'''
print(f"a ref count is {sys.getrefcount(a)}") 
''' # python internal get refer count but a is double 
count, due to passing the argumenet into a function
write a function with c code, we pass the address of 
the variable instead of variable name '''
import ctypes 
def ref_count(address: int):
    return ctypes.c_long.from_address(address).value
print(f"a cref count is : {ref_count(id(a))}")
b = a
print(f"b address is {hex(id(b))}")
print(f"a cref count is : {ref_count(id(a))}") 
# id(a) is done then pass into ref_count
#  
b = None
print(f"b address is gone {hex(id(b))}")
'''keep the id of a and see what happen after 
a is pointing to other value '''
a_id = id(a) 
a = None
print(f"a address content {ref_count(a_id)}")
# check the address
c = 10
d=11
print(f"a address content is {ref_count(a_id)}")
INFO