variable variables

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Jun 18 08:37:33 EDT 2010


someone a écrit :
> On Jun 18, 2:05 pm, Bruno Desthuilliers <bruno.
> 42.desthuilli... at websiteburo.invalid> wrote:
(snip)
>>
>> Still has a "code smell" thing to me, but hard to say not knowing the
>> real code and context.
> 
> sorry, code is not about printing variables rather accessing, it's
> just example.

Yeps, this I understood - hence the  "but..." part of the sentence. What 
I dislike the most here is the obj.otherobj.yetanother.attrib stuff - 
might be ok in this case but it's an obvious violation of the law of 
Demeter (=> AKA: only talk to your neighbour).

But anyway - if Foo only needs to know about someobject.A and Bar only 
needs to know about someobject.B, then resolve them once:


from some_module import some_object

class Foo:
     def __init__(self):
         self.type = 'A'

     def printAttr(self):
         target = getattr(someobject, self.type)
	target.B
         target.C
         target.D
         # etc...


This will also save a couple useless lookups. In fact, aliasing a 
commonly accessed attribute (or method) to a local name is an old time 
Python micro-optimization.




More information about the Python-list mailing list