162. Managing Memory with gc Module

Snippet 1: Manual Garbage Collection

Copy

import gc

# Force garbage collection
gc.collect()

print("Manual garbage collection completed.")

Snippet 2: Disable Automatic Garbage Collection

Copy

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

Copy


Snippet 4: Get Garbage Collector's Thresholds

Copy


Snippet 5: Get Objects Tracked by the Garbage Collector

Copy


Snippet 6: Disable Garbage Collection Temporarily

Copy


Snippet 7: Set Garbage Collection Thresholds

Copy


Snippet 8: Check for Unreachable Objects

Copy


Snippet 9: Force Garbage Collection for Unreferenced Objects

Copy


Snippet 10: Track Objects Using gc.set_debug()

Copy

Last updated