Search code examples
pythongetattr

What's the best way to get referenced object (variable level)


Let's assume, the following case:

class foo(object):
    def __init__(self, ref=None):
        self.ref = ref

    def __str__(self):
        return "I'm foolish"

f = foo()
f.ref = foo()
f.ref.ref = foo()
f.ref.ref.ref = foo()

Trying print(getattr(f, "ref.ref.ref"))

raises 'foo' object has no attribute 'ref.ref.ref'.

So, I resolved the issue with the following function:

def get_ref(ref_attr):
    for attr in ref_attr.split('.'):
        print(getattr(f, attr))

get_ref("ref.ref.ref") retruns the expected result:
I'm foolish
I'm foolish
I'm foolish

I wonder myself, if is an another way to do this or a built-in method that i could used.

Thanks.


Solution

  • That's not doing what you think: it's getting the first element each time. It only appears to work because all the levels are called "ref". If you called them 'foo.bar.baz' it would fail. You need to actually use the element from the last iteration each time:

    def get_ref(ref_attr):
        item = f
        for attr in ref_attr.split('.'):
            item = getattr(item, attr)
            print item
    

    But no, there's no built-in way of doing this.