Reading Python from config files

I have a python class that reads a config file using ConfigParser:

Configuration file:

[geography]
Xmin=6.6
Xmax=18.6
Ymin=36.6
YMax=47.1

      

Python code:

class Slicer:
    def __init__(self, config_file_name):
        config = ConfigParser.ConfigParser()
        config.read(config_file_name)
        # Rad the lines from the file
        self.x_min = config.getfloat('geography', 'xmin')
        self.x_max = config.getfloat('geography', 'xmax')
        self.y_min = config.getfloat('geography', 'ymin')
        self.y_max = config.getfloat('geography', 'ymax')

      

I feel like the last four lines are being repeated and must somehow shrink to a single Pythonic line that would create a variable self.item

for each item in the section.

Any ideas?

Adam

UPDATE:

Following your answers, I changed my code to:

    for item in config.items('geography'):
        setattr(self, '_'+item[0], float(item[1]))

      

Now,

   print self.__dict__
   >>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001, 
        '_ymin': 36.600000000000001, '_xmin': 6.5999999999999996}

      

+2


source to share


3 answers


for line in ['x_min', 'x_max', 'y_min', 'y_max']:

   setattr(self, line, config.getfloat('geography', line.replace('_', '')))

      



+3


source


I usually try to avoid external interactions in the constructor - it's hard to validate the code. Better to pass a config parser instance or an object like fp instead of a filename.



+5


source


How about something like:

for key in ['xmin', 'xmax', 'ymin', 'ymax']:
    self .__ dict __ [key] = config.getfloat ('geography', key);

Note that the above will assign it to self.xmin instead of self.x_min ... however, if you are ok with that naming, then this should work ... otherwise the mapping between the names will be more code than the original.

+1


source







All Articles