Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List live objects of certain type in current Python interpreter.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import gc
def list_live_objects(ty=None):
def go(results, elements, bitset):
for elem in elements:
identity = id(elem)
if identity in bitset:
continue
bitset.add(identity)
if ty is None or isinstance(elem, ty):
results.append(elem)
referents = gc.get_referents(elem)
if referents:
go(results, referents, bitset)
elements = gc.get_objects()
results = []
bitset = set()
go(results, elements, bitset)
return results
################ examples ###############################
def list_objects():
return list_live_objects()
def list_lists():
return list_live_objects(list)
def list_ndarrays():
import numpy
return list_live_objects(numpy.ndarray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment