rzar
rzar

Reputation: 601

How to use @property properly

How to rewrite the following example in order to properly use @property?

class Config:
    def __init__(self, config_folder="", config_file="config.json"):
        self.set_config(config_folder, config_file)

    def get_config(self):
        with open(self.config) as f:
            return json.load(f)

    def set_config(self, config_folder, config_file):
        self.BASE_DIR = pathlib.Path(__file__).parent
        self.config = self.BASE_DIR / config_folder / config_file

Upvotes: 0

Views: 63

Answers (2)

Nick Bastin
Nick Bastin

Reputation: 31329

For starters, you can't pass multiple values using a property, so your set_config can't be a property as currently constructed.

Also, it's worth pointing out that your get_config and set_config don't really match, logically - get_config gives you the contents of a file, while set_config, instead of setting the contents, just sets the path name. This type of asymmetry can lead to confusing bugs.

If you wanted to make this a property you might want to do it as two different things - one that gets/sets the path for on-disk storage, if that is important to manipulate, and one that gets/sets the actual data contents of the currently configured path.

Upvotes: 3

Graipher
Graipher

Reputation: 7186

Just move the definitions of the path of the config file into the constructor:

class Config:
    def __init__(self, config_folder="", config_file="config.json"):
        self.base_dir = pathlib.Path(__file__).parent
        self.config_path = self.base_dir / config_folder / config_file

    @property
    def config(self):
        with open(self.config_path) as f:
            return json.load(f)

If you want to overwrite the config path afterwards, you can do just that by changing the attribute directly (note that it is the config_path attribute, not the config attribute):

conf = Config()
conf.config_path = "./other_config.json"
print(conf.config)

Alternatively you could keep a method like your set_config (probably better called set_config_path) around to deal with the base_dir.

Upvotes: 2

Related Questions