Aleks Kuznetsov
Aleks Kuznetsov

Reputation: 570

How to recreate object from class in Python?

I have a simple class that loads json and converts it into dict.

class Config(dict):
    def __init__(self, config_path):
        with open(config_path) as f:
            data = json.load(f)
            super().__init__(**data)

I create an instance of a class by passing file location:

config = Config(os.environ['CONFIG_PATH'])

How can I recreate the object with the same parameter, but without passing this parameter? E.g. read file from the same path again.

I know, that I can simply pass the parameter again, create a new object and assign it to the same variable. I'm wondering if there is a common pattern for that.

In the end, I want to be able to do something like:

if something:
   config = config.reload()
# OR even
   config.reload()

Upvotes: 0

Views: 594

Answers (1)

Masklinn
Masklinn

Reputation: 42492

You'd have to assign the path as an instance variable (so it remains available) e.g. self._path = config_path, then you can just add a method updating the internal state based on re-reading the file e.g.

def reload(self):
    with open(self._path) as f:
        self.update(json.load(f))

Upvotes: 1

Related Questions