3

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?

1 Answer 1

1

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.

2
  • Thanks for thinking about my question. I should have written this is the question, but I would also like to do more complicated things like accessing variables in objects which are stored in lists in other objects, hence the method by which attributes are accessed is important.
    – mskel
    Oct 13, 2012 at 3:18
  • @mskel I would still try to make it unintrusive. Maybe complicate the iterative_getattr function and the access descriptor (replace plain list of attr names with something more complicated) but try not to implement the access logic in the accessed classes. Then you get a mechanism that works for free on any class. Oct 14, 2012 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.