Last active
May 26, 2025 20:25
-
-
Save JnyJny/e41884e9ea99310a69dc7ad1d4d3b4d6 to your computer and use it in GitHub Desktop.
A Python Mixin Class that Remembers Instances
This file contains hidden or 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
from __future__ import annotations | |
import gc | |
import sys | |
import weakref | |
class InstancesMixin: | |
def __new__(cls, *args, **kwargs) -> Class: | |
instance = super().__new__(cls) | |
cls.instances.add(instance) | |
return instance | |
class Foo(InstancesMixin): | |
instances = weakref.WeakSet() | |
foo = Foo() | |
bar = Foo() | |
baz = Foo() | |
qux = Foo() | |
print(Foo.instances) | |
del foo | |
gc.collect() | |
print(Foo.instances) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment