Maths12
Maths12

Reputation: 991

How can i call this class with a default file location if none is specified?

package_name
│   setup.py
│
├───package_name
│      │───config 
│      │   -config_reader.py
│      │  
│      │───model_configs 
│      │      - model.yml 
│      │-__init__.py

I am new to package making so i hope the above folder structure is OK. Inside package_name/package_name/config/ i have config_reader.py which looks like:

import os
import sys
import yaml
from copy import deepcopy

class Config: 
    
    def __init__(self,config_file_path='../model_configs/model.yml'):
        try: 
            with open(config_file_path,'r') as cfg_file:
                self.config = yaml.load(cfg_file)
        except FileNotFoundError as fe: 
            print("config not found")
            sys.exit(2)
        
        self.EXTRACTION_CONFIG = self.config['data_extraction']
        self.TRAINING = self.config['model_build']
        self.ALL = self.config

when i open a notebook in the first package_name folder and run:

from package_name.config.config_reader import Config as config  
              
config = config()

it says file not found quoting the path '../model_configs/model.yml'. Now i know this is because of the current directory i am in, e.g. i would have to specify the location of the config file which would not be package_name/model_configs/model.yml... but is there a way to adapt the function such that if empty ^ as above i.e. config() for it to take the default? I thought by specifying the string of path in the class would help it take default but it is not taking it.

How can i do this?

Upvotes: 0

Views: 245

Answers (1)

Try something like this:

class Config: 
    
    def __init__(self,config_file_path=None):
        config_file_path = config_file_path or os.path.join( os.path.split(__file__)[0], '../model_configs/model.yml' )
        try: 
            with open(config_file_path,'r') as cfg_file:
                self.config = yaml.load(cfg_file)
        except FileNotFoundError as fe: 
            print("config not found")
            sys.exit(2)

don't have setup to try it, but what this does is, if no config_file_path is specified in the class instantiation, use the current file in __file__ (i.e. path to config_reader.py) to get the path to the current file then append the relative path to the yml file.

Upvotes: 1

Related Questions