pymongo and attribute dictionaries

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Feb 4 20:58:22 EST 2015


Ian Kelly wrote:

>> Extending this to wrap methods of classes is also left as an exercise.
>> (Hint: don't subclass. Search the ActiveState Python recipes for
>> "automatic delegation" by Alex Martelli.)
> 
> Do you mean this one?
> 
> http://code.activestate.com/recipes/52295-automatic-delegation-as-an-
alternative-to-inherita/
> 
> That's based on old-style classes. With new-style classes it fails to
> delegate dunder methods like __str__. That recipe should be considered
> obsolete.

I'm aware of the problem with dunder methods. But that's not an 
insurmountable problem, if you need your delegation recipe to support 
dunders (and you may not), it's fiddly and annoying to do so, but not 
impossible. There are at least two approaches:

- manually delegate to the dunders that you care about with hand-
  written dunder methods:

    def __str__(self):
        return type(self.proxied_object).__str__(self.proxied_object)
        # or for people who prefer simplicity over correctness
        # return self.proxied_object.__str__()


- write a decorator which inspects the class and automatically adds 
  explicit dunders for you. (There's a recipe on ActiveState for 
  that one too.)

Regardless of whether you start with Alex's recipe or not, the idea is to 
make a proxy for the pymongo classes, and delegate to it rather than 
subclass or re-invent the wheel. That's a basic design pattern, and if 
dunders are a problem in Python that Ruby or Java doesn't have, oh well, 
life wasn't meant to be easy.



-- 
Steven




More information about the Python-list mailing list