1

I'm trying to override dict class in a way that is compatible with standard dict class. How I can get access to parent dict attribute if I override __getitem__ method?

class CSJSON(dict):
    def __getitem__(self, Key : str):
       Key = Key + 'zzz' # sample of key modification for app use
       return(super()[Key])

Then I receive error:

'super' object is not subscriptable.

If I use self[Key] then I get infinite recursive call of __getitem__.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

2

You have to explicitly invoke __getitem__, syntax techniques like [Key] don't work on super() objects (because they don't implement __getitem__ at the class level, which is how [] is looked up when used as syntax):

class CSJSON(dict):
    def __getitem__(self, Key : str):
       Key = Key + 'zzz' # sample of key modification for app use
       return super().__getitem__(Key)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Depending on your needs, working from collections.UserDict or abc.MutableMapping might be less painful than directly subclassing dict. There are some good discussions here about the options: 1, 2, 3

How I can get access to parent dict attribute if I override getitem method?

More experienced users here seem to prefer MutableMapping, but UserDict provides a convenient solution to this part of your question by exposing a .data dict you can manipulate as a normal dict.

Chris Keefe
  • 797
  • 7
  • 17