Search code examples
pythonreferencebreadcrumbs

Keeping 'breadcrumbs' to object data in Python


I've run into the following pattern a couple of times while designing nosql database applications in Python:

What I want is to dynamically store a reference to some data in an object hierarchy which will let me both access the data and know where it is in the hierarchy.

For example, suppose I have an object structure like:

class A(object):
    def __init__(self, val1, val2):
        self.val1 = val1
        self.val2 = val2

class B(object):
     def __init__(self, a):
          # a is an instance of A
          self.a = a

class C(object):
     def __init__(self, b):
          # b is an instance of B
          self.b = b

a = A(0,1)
b = B(a)
c = C(b)

Now, I want to refer (dynamically) to some data that exists deep inside the c object.
Let's say I want to refer to the val1 of A inside the B in c. What I'm doing is making a 'breadcrumb' tuple ('b', 'a', 'val1') to refer to the data. Then, I'll make any class that I want to refer to with these breadcrumbs inherit from a base class say Breadcrumb, which defines methods to parse the breadcrumb recursively and use getattr to return the data which it refers to.

Is this a pattern? Anti-pattern? Is there a way to do this more simply, or to re-design my program so I don't have to?


Solution

  • I don't see much benefit in being intrusive to the classes you access (introducing superclass counts as intrusive.) Why do they need to know whether their attributes are accessed this or that way? They already support getattr which is all you need to implement this.

    I would just write a free function iterative_getattr(obj, attrs) (maybe with a better name) which works on any object and accesses the chain of attributes defined by the attrs tuple.