Skip to content

Instantly share code, notes, and snippets.

@JnyJny
Last active May 26, 2025 20:25
Show Gist options
  • Save JnyJny/e41884e9ea99310a69dc7ad1d4d3b4d6 to your computer and use it in GitHub Desktop.
Save JnyJny/e41884e9ea99310a69dc7ad1d4d3b4d6 to your computer and use it in GitHub Desktop.
A Python Mixin Class that Remembers Instances
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