New PEP: Attribute Access Handlers

Bjorn Pettersen bjorn at roguewave.com
Sat Jul 22 01:40:42 EDT 2000


Paul Prescod wrote:
> 
> Bjorn Pettersen wrote:
> >
> > Justification, Scenario 4:
> >
> >    An existing class has a string attribute, however the most common
> > operation on it is appending to the end. Through the profiler you find
> > that this operation is taking up 95% of the applications time. You want
> > to change the implementation to cStringIO for efficiency (total
> > execution time for your application goes from 90 seconds to 3 secs).
> 
> Actually, I'm not sure if my proposal would help here. Appending to a
> cStringIO is not an assignment operation...

The only requirement was that the attribute access (myObject.property)
stay the same, only instead of returning a string it would compute
.value() on the cStringIO object. I.e., original:

  class MyObject:
    def __init__(self,s):
      self.s = s

new version:

  class MyObject:
    def __init__(self,s):
      self._s = cStringIO.StringIO(s)
    def __getattr__(self, a):
      if a == 's':
        return self.__dict__['_s'].value()
      else:
        return self.__dict__[a]

so client code could continue looking like:

  myObject = MyObject('foobar')
  s = myObject.s

> > Perhaps you should add a few words about why you chose __attr_XXX__
> > instead of __set/get/del_XXX__?
> 
> That was actually the first proposal. But inheritance could get
> confusing if you inherited set without get or get without set etc.

Hmmm... I'm not quite sure I understand... With __set/get/del_XXX__
defined in a superclass you would automatically inherit all of them and
could choose to only override one of them, e.g. if you wanted to perform
further checks on a set but the get was the same.  With __attr_XXX__ you
would have to explicitly call the superclass' __attr_XXX__ method if you
didn't define all of set/get/del(?)  I have a feeling I'm missing
something...

-- bjorn




More information about the Python-list mailing list