Subclassing dict to give it inital values from a JSON file doesn't work as expected

65 views Asked by At

I come from a C/C++ background

I would like to subclass dict to make one that automatically opens a JSON file. Here's the code and problem:

class DictFromJSON(dict):
    def get_from_file(self, filename):
        with open(filename,) as file_reader:
            self = json.load(file_reader)
        print(self)

    def save(self, filename):
        with open(filename, "w") as file_writer:
            json.dump(self, file_writer)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.save()

    def __init__(self, filename, *args):
        super().__init__(args)
        self.get_from_file(filename)

json_dict = DictFromJSON("myjson.json")
print(json_dict)

The JSON file for testing contains a single variable mykey

this outputs:

{'mykey': True}
{}

So it's opening the file correctly, print(self) outputs the expected results, but when I print a variable made with the class it's still empty.

I've tried assigning self from json.load() a few different ways, including iterating through keys, but that didn't work either

1

There are 1 answers

7
chepner On

Assigning to the local name self does not update the object. You need to use update:

class DictFromJSON(dict):
    def get_from_file(self, filename):
        with open(filename,) as file_reader:
            self.update(json.load(file_reader))

    def save(self, filename):
        with open(filename, "w") as file_writer:
            json.dump(self, file_writer)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.save()

    def __init__(self, filename, *args):
        super().__init__(args)
        self.get_from_file(filename)