Skip to content

Instantly share code, notes, and snippets.

@sighingnow
Last active March 16, 2021 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sighingnow/dbe8b05483a786855e4d498019419cc4 to your computer and use it in GitHub Desktop.
Save sighingnow/dbe8b05483a786855e4d498019419cc4 to your computer and use it in GitHub Desktop.
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