Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I get a list of all instances of a given class in Python?
Python provides several ways to get a list of all instances of a given class. The most common approaches use the gc module or the weakref module. The gc module is part of Python's standard library and doesn't need separate installation.
Using the gc Module
The gc (garbage collector) module allows you to access all objects tracked by Python's garbage collector. You can filter these to find instances of a specific class ?
import gc
# Create a class
class Demo:
pass
# Create four instances
ob1 = Demo()
ob2 = Demo()
ob3 = Demo()
ob4 = Demo()
# Find all instances of Demo class
instances = []
for obj in gc.get_objects():
if isinstance(obj, Demo):
instances.append(obj)
print(f"Found {len(instances)} instances:")
for instance in instances:
print(instance)
Found 4 instances: <__main__.Demo object at 0x000001E0A407FC10> <__main__.Demo object at 0x000001E0A407EBC0> <__main__.Demo object at 0x000001E0A407EBF0> <__main__.Demo object at 0x000001E0A407EC20>
Counting Instances with gc
You can also count the number of instances without storing them ?
import gc
class Demo:
pass
# Create instances
ob1 = Demo()
ob2 = Demo()
ob3 = Demo()
ob4 = Demo()
# Count instances using generator expression
count = sum(1 for obj in gc.get_objects() if isinstance(obj, Demo))
print(f"Total instances: {count}")
Total instances: 4
Using weakref for Instance Tracking
The weakref module provides a more elegant solution by maintaining a registry of instances within the class itself ?
import weakref
class Demo:
_instances = []
def __init__(self, name=None):
# Store weak reference to avoid circular references
self.__class__._instances.append(weakref.ref(self))
self.name = name
@classmethod
def get_instances(cls):
# Return live instances (filter out dead references)
return [ref() for ref in cls._instances if ref() is not None]
# Create instances
ob1 = Demo('Object1')
ob2 = Demo('Object2')
ob3 = Demo('Object3')
# Get all instances
instances = Demo.get_instances()
print(f"Active instances: {len(instances)}")
for instance in instances:
print(f"Name: {instance.name}")
Active instances: 3 Name: Object1 Name: Object2 Name: Object3
Comparison of Methods
| Method | Performance | Memory Impact | Best For |
|---|---|---|---|
gc.get_objects() |
Slow (scans all objects) | No extra memory | Debugging, one-time checks |
weakref tracking |
Fast | Minimal overhead | Production code, frequent access |
Conclusion
Use gc.get_objects() for debugging or occasional instance checking. For production applications that need frequent access to instances, implement weakref-based tracking within your class for better performance.
