Search code examples
pythonintrospection

How to use introspection in Python 2.7 to find instances of certain class in a module?


I have a Python module that defines a classes and instantiates a number of instances of that classes. I would like to write a test that the correct number have been instantiated.

bar = Foo('abc')
baz = Foo('def')
...
quz = Foo('xyz')

Then in testing I have tried things like:

assert num = len([ x for x in dir(foo) if isinstance(x, foo.Foo)])    

which doesn't work, because dir(foo) seems to give a list of Strings.

Is there a way to find the instances of a particular class in a module?


Solution

  • You're really close. Use a double equals sign for comparison, and you need to use getattr() to retrieve the module member by name:

    assert num == len([getattr(foo, x) 
                       for x in dir(foo) 
                       if isinstance(getattr(foo, x), foo.Foo)])
    

    Might also be helpful to read the documentation on dir().