Python update of inherited level dictionary

I am looking for a simple and easy way to update class-level dictionaries that are inherited from base classes. For instance:

class Foo(object): adict = {'a' : 1} class Bar(Foo): adict.update({'b' : 2}) # this errors out since it can't find adict 

so that:

 Foo.adict == {'a' : 1} Bar.adict == {'a' : 1, 'b' : 2} 

I would prefer not to use instances here and, if possible, not to use class methods.

+4
source share
4 answers

Note that even if this worked, you should update the same dictionary instead of creating a new one (so Foo.adict is Bar.adict and therefore Foo.adict == Bar.adict ).

In any case, the easiest way is to explicitly reference the parent class dict (and copy it, see above):

 class Bar(Foo): adict = dict(Foo.adict) adict.update({'b': 2}) 
+3
source

"I would rather not use instances here and, if possible, not use class methods."

Right So do not do this.

 foo_adict = {'a' : 1} def B(): foo_adict.update({'b': 2}) 

I'm not sure why you use class attribute level dictionaries; it rarely behaves in a useful or expected way.

0
source

I also met this problem. I solved this with a metaclass that can also work with multiple inheritance:

 import six class CheckerMeta(type): def __new__(cls, name, bases, attrs): new_class = super(CheckerMeta, cls).__new__(cls, name, bases, attrs) base_configs = [bc.config for bc in bases if hasattr(bc, 'config')] configs = base_configs + [new_class.config] new_class.config = {} for config in configs: new_class.config.update(config) return new_class class BaseChecker(six.with_metaclass(CheckerMeta)): config = {} class CheckerA(BaseChecker): config = {'a': 1} class CheckerB(BaseChecker): config = {'b': 2} class CheckerC(CheckerA, CheckerB): config = {'c': 3} assert CheckerA.config == {'a': 1} assert CheckerB.config == {'b': 2} assert CheckerC.config == {'a': 1, 'b': 2, 'c':3} 
0
source

Initialize adict in the Foo class and in Bar initialize by calling init from super , then update .

 class Foo(object): def __init__(self): self.adict = {'a': 1} class Bar(Foo): def __init__(self): super(Bar, self).__init__() self.adict.update({'b': 2}) 

Example:

 In [14]: b = Bar() In [15]: b.adict Out[15]: {'a': 1, 'b': 2} 
0
source

Source: https://habr.com/ru/post/1388174/


All Articles