using __getitem()__ correctly

Charles T. Smith cts.private.yahoo at gmail.com
Wed Dec 30 17:54:44 EST 2015


On Wed, 30 Dec 2015 13:40:44 -0700, Ian Kelly wrote:

> On Wed, Dec 30, 2015 at 9:58 AM, Charles T. Smith
>> The problem is that then triggers the __getitem__() method and I don't
>> know how to get to the attributes without triggering __getattr__().
>>
>> It's the interplay of the two that's killing me.
> 
> The only interplay of the two is what you have written into your class.
> 
>> In the example, if I have:
>>
>>   self.mcc = self.attrs.mcc
>>
>>
>> The crux:
>>
>> Then __getattr__() triggers for the mcc.  If I try to use
>> self.attrs['mcc'] to get it, then that triggers __getitem__().  Okay,
>> if the key is not an int, I'll go and get it and return it...
>> unfortunately that triggers __getattr__(), an infinite loop.
> 
> How precisely are you trying to store these: as an attribute, or as a
> dict item? If it's supposed to be in the dict, then why is your
> __getitem__ trying to look up an attribute to begin with?



I don't understand this distinction between an "attribute" and a "dict item".
attrdict is a stupid legacy class that inherits from a dictionary.  I think
the intent was to be faster than a normal class, but I doubt there's any value
to that.

In any case, I thought that class attributes were, in fact, items of __dict__?

The reason that my __getitem__() is trying to look up an attribute is, I
think, because this syntax triggers __getitem__ with a key of "mcc":

  return self[name]

Is that assumption wrong?  That was the reason I was looking to find
another way to get at the attributes, because
  return self.__getattr__(name)
does, too, and this doesn't even find them:
  return self.__getattribute__(name)

Just to establish the concept, this horrible thing is showing some promise:

  attriter = self.iteritems()
  for attr in attriter:
      if attr[0] == name:
          return attr[1]


(because the subscripts there are on a tuple type)

But I concede I must be doing something fundamentally wrong because this
assert is triggering:
    def __getattr__ (self, name):
        print "attrdict:av:__getattr__: entered for ", name
        assert name not in self.keys(), "attrdict:__getattr__: who lied?"
 
  





More information about the Python-list mailing list