# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Reference Counting
#
# When variables are created, Python maintains a reference count.  It uses this non-zero count to know if the memory location is being used.
#
# Getting reference count
#
# - sys.getrefcount(variable) <-- this also creates an extra count
# - ctypes.c_long.from_address(address).value <-- address is an integer so it does not affect teh reference count

import sys

a = [1, 2, 3]


id(a)

sys.getrefcount(a)

import ctypes


def ref_count(address: int):
    return ctypes.c_long.from_address(address).value


ref_count(id(a))

b = a

id(b)

ref_count(id(a))

c = a
ref_count(id(a))

c = 10
ref_count(id(a))

b = None

ref_count(id(a))

a_id = id(a)
a = None
ref_count(a_id)

# After references is 0, Python is free to reuse the memory location for other
# objects
ref_count(a_id)

StarcoderdataJupyterScriptsDedupFiltered