Program Questions
Program Questions

Reputation: 450

how to find instances of a class at runtime in python

how to find instances of a class at runtime in python

eg.

class Foo():
    pass

class Bar(Foo):
    def __init__(self, a):
            print a

inst_b1 = Bar(3)
inst_b2 = Bar('Hello World!!!')

How would i find out how many instances of class Bar exists and there names at runtime?

Also, as i want to use them at runtime what would be the better solution to have them in a custom dict or get it from the universal dict of variables(using vars()).

Thanks

Upvotes: 1

Views: 181

Answers (2)

John Peters
John Peters

Reputation: 1179

How many can be done thus:

import gc
n_Bars = sum(1 for obj in gc.get_objects() if isinstance(obj,Bar))

If you also want their names, you may be better off using a dict instead of separate variables.

Edit: I just thought of a hack to get the names too:

for obj_name in dir():
    if isinstance(eval(obj_name), Bar):
        print obj_name

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113948

class Bar(Foo):
    instances = []
    def __init__(self, a):
            print a
            Bar.instances.append(self)

inst_b1 = Bar(3)
inst_b2 = Bar('Hello World!!!')
print len(Bar.instances)
print Bar.instances

Its much more complicated to get the variable name you assigned to it...

Upvotes: 3

Related Questions