Last active
March 16, 2021 06:41
-
-
Save sighingnow/dbe8b05483a786855e4d498019419cc4 to your computer and use it in GitHub Desktop.
List live objects of certain type in current Python interpreter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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