Search code examples
pythonintrospection

Finding what list a class instance is in, in Python


This problem is thus: I have an instance of a class, I want to know what list it is a part of, i.e. :

class test_class() :
    def test() :
        print 'I am a member of list', parent_list

foo = [test_class(), 52, 63]
bar = ['spam', 'eggs']
foo[0].test()

I would like to print out I am a member of list foo. There are an arbitrary number of lists that any given instance of test_class() could belong to.


Solution

  • First of all, I don't know what could be the use-case for it, because ideally while putting objects in list, you can track them via a dict or even if you have list of all lists you can just check for objects in them, so a better design wouldn't need such search.

    So lets suppose for fun we want to know which lists a object is in. We can utilize the fact that gc knows about all objects and who refers to it, so here is a which_list function which tells which lists refer to it ( that necessarily doesn't mean it contains it)

    import gc
    
    class A(object): pass
    class B(A): pass
    
    def which_list(self):
        lists_referring_to_me = []
        for obj in gc.get_referrers(self):
            if isinstance(obj, list):
                lists_referring_to_me.append(obj)
    
        return lists_referring_to_me
    
    
    a = A()
    b = B()
    foo = [a, 52, b]
    bar = ['spam', b]
    
    print which_list(a)
    print which_list(b)
    

    output:

    [[<__main__.A object at 0x00B7FAD0>, 52, <__main__.B object at 0x00B7FAF0>]]
    [[<__main__.A object at 0x00B7FAD0>, 52, <__main__.B object at 0x00B7FAF0>], ['spam', <__main__.B object at 0x00B7FAF0>]]