[Tutor] How to find all current instances of a class?
boB Stepp
robertvstepp at gmail.com
Sun Jun 21 19:41:02 EDT 2020
On Sun, Jun 21, 2020 at 2:47 PM Mats Wichmann <mats at wichmann.us> wrote:
>
> On 6/21/20 1:34 PM, boB Stepp wrote:
> > I had (perhaps) naively hoped that classes had dunder methods to list
> > all current instances associated with that class, but if there is
> > something that simple I have yet to find it. Does an easy, built-in
> > method exist to list all current instances of a particular class?
>
> Python doesn't track this, so you gotta do it yourself.
> For the former, I *think* this will be good enough, it's off the top of
> my head and so untested:
>
> import gc
>
> instances = [obj for obj in gc.get_objects() if isinstance(obj,
> ClassWeWantToTrack)]
Thanks, Mats, that does the trick quite nicely. My interest in this
stems from exploring all the *hidden* information that is available
about classes and their instances. After seeing all of the available
information it struck me that I had not seen anything tracking
instances. But what you and Alan say makes sense -- may be many such
instances which would take unnecessary additional resources to track.
--
boB
More information about the Tutor
mailing list