162. Managing Memory with gc Module

Snippet 1: Manual Garbage Collection

import gc

# Force garbage collection
gc.collect()

print("Manual garbage collection completed.")

Snippet 2: Disable Automatic Garbage Collection

import gc

# Disable automatic garbage collection
gc.disable()

# Do some memory-intensive operations here...

print("Automatic garbage collection is disabled.")

Snippet 3: Enable Automatic Garbage Collection

import gc

# Enable automatic garbage collection
gc.enable()

# Do some memory-intensive operations here...

print("Automatic garbage collection is enabled.")

Snippet 4: Get Garbage Collector's Thresholds


Snippet 5: Get Objects Tracked by the Garbage Collector


Snippet 6: Disable Garbage Collection Temporarily


Snippet 7: Set Garbage Collection Thresholds


Snippet 8: Check for Unreachable Objects


Snippet 9: Force Garbage Collection for Unreferenced Objects


Snippet 10: Track Objects Using gc.set_debug()

Last updated