Python recursively __getattribute__
usenot at geekmail.INVALID
Mon Nov 22 18:00:42 CET 2010
On Mon, 22 Nov 2010 08:41:49 -0800 (PST) Roman Dolgiy <tosters at gmail.com> wrote:
> On Nov 22, 6:04 pm, Andreas Waldenburger <use... at geekmail.INVALID>
> > On Mon, 22 Nov 2010 07:46:47 -0800 (PST) Roman Dolgiy
> > <tost... at gmail.com> wrote:
> > > Hello,
> > > I need to implement such behavior:
> > > obj.attr1.attr2.attr3 --> obj.attr1__attr2__attr3
> > > It looks like I have to override obj's class __getattribute__ and
> > > also use python descriptors somehow.
> > > Any help will be much appreciated.
> > >http://stackoverflow.com/questions/4247036/python-recursively-getattr...
> > Why? No, really: Why?
> > [...]
> I have a django project.
> obj is django-haystack's SearchResult instance, it contains a lot of
> de-normalized data (user__name, user__address) from django model, and
> I need to access it as result.user.name for compability reasons.
I don't know anything about django, so I may be babbling nonsense. Caveat emptor.
How about taking your "user__whatever" thingies and have a function emit customized result instances. For this you can just create a plain object subclass, say ResultElement. If these "user__whatever" thingies are strings (you haven't told), split them by "__" and create a new plain object for every level of attributes, attaching it to the previous level.
You can probably make your life easier if you use defaultdicts first and then translate these to your object hierarchy.
That's how I'd do it. I don't know if that helps you. If not, please provide more info.
To reach me via email, replace INVALID with the country code of my home
country. But if you spam me, I'll be one sour Kraut.
More information about the Python-list