Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A dict subclass instance is empty after initialization

I try to inherit a dict class, by implementing some logic during the initialization. To do so I add some of the key-value pairs in __init()__ method.

However, after initialization, the instance of my child class is always empty.

import copy
class my_dict(dict):
    def __init__(self, raw_dict):
        self = copy.deepcopy(raw_dict)
        self['bar'] = raw_dict['foo']


original = {'foo' : 'apple'}
alfa = my_dict(original)
print(alfa) 

prints empty dict while the expectation would be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{'foo': 'apple', 'bar': 'apple'}]

How can I achieve the desired behaviour?

>Solution :

You can use the super constructor to do the effect you are looking for:

import copy
class my_dict(dict):
    def __init__(self, raw_dict):
        super().__init__(copy.deepcopy(raw_dict))
        self['bar'] = raw_dict['foo']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading