I have a class whose instance variables should be initialized from a file ('settings.json'). That file does not always exist or is sometimes not filled with useful values, so I have to check for that first. I am now wondering what the best practice would be, I currently see two options but I am open to better ones.
Check if the file exists and contains useful information in
__init__()
and then create and fill the instance variables:class Settings: def __init__(self): if file.exists() and contains_useful_information(): self.dir_path = "path/to/dir" ... else: # ask for user input pass
First create placeholders and fill them later after checking the file.
class Settings: def __init__(self): self.dir_path = "" self.check_file() def check_file(self): # check if file exists and contains useful values, otherwise ask user for input self.dir_path = "path/to/dir"
I don't really like putting this much logic into __init__()
but I don't see a better solution.
Background: I'm using PyQt5 to build a GUI. I currently have two classes, one that deals with the actual graphical interface and one that deals with settings (e.g. directory paths). Since I want some of these settings to be available to the user without reentering them every time, they are saved in a settings file.
This is the first time I'm using OOP in Python or rather in general, so I'm not really sure. I found https://stackoverflow.com/questions/5875902/how-to-initialize-a-class-with-data-from-a-python-file and this https://codereview.stackexchange.com/questions/104841/read-file-into-list-when-class-is-instantiated-in-python-2-7, but they are both not really solving my problem, since the first does not contain logic and the second is something I can solve without using a class.
Edit: I now found these questions: Pattern for creating an instance of a class from a UI form and Instantiate a class from a config file. Where should the parse function go?. While these are nearer to my question, I still feel they do not completely answer my question, as they both do the parsing somewhere else. I could also do this like suggested in the second question in the main function before calling the class. Would that be a better option?
check_file
method is missing theself
parameter. Check below for the answer I provided.