1

I have a yaml configuration file (configuration.yaml).

Which I load using:

import yaml

configuration = load_configurations()
def load_configurations(path_configuration = "../input/configuration.yaml"):
    with open(path_configuration, "r") as stream:
        try:
            return(yaml.safe_load(stream))
        except yaml.YAMLError as exc:
            print(exc)

Within configuration I have the following structure:

parameters:
   pmt1:
      value: 1.0
      description: some text
   pmt2:
      value: 0.03
      description: some other text
   pmt3:
      value: 0.033
      description: more text
...
...
   pmtN:
      value: 0.04
      description: yet more text

Now, I would like to import these parameters as objects in a class whose value is the value taken from the configuration file.

I read the YAML documentation and following previously asked questions:

Convert nested Python dict to object?

Converting dictionary to an object with keys as object's name in Python

But I haven't been able to solve my issue.

What I managed to do until now is:

class MyClass:

    def __init__(self, configuration):
        self.set_parameters(configuration)


    def set_parameters(self, configuration):
        self.__dict__ = configuration["parameters"]    

Which works but only allows me to call something like:

In[]: MyClass.pmt1
Out[]: 
{'value': 1,
 'description': 'some text'}

What I would like to get:

In[]: MyClass.pmt1
Out[]: 1

I also tried to iterate through the dictionary items for item in configuration['parameters'].items(): but that returns a tuple of the form:

('pmt1', {'value': 1.0, 'description': 'some text'}) 

but I'm not sure how to continue from here.

CAPSLOCK
  • 6,243
  • 3
  • 33
  • 56

2 Answers2

3

I'd use setattr rather than overwriting __dict__, which could have unexpected consequences.

class MyClass:

    def __init__(self, configuration):
        self.set_parameters(configuration)

    def set_parameters(self, configuration):
        for k, v in configuration["parameters"].items():
            setattr(self, k, v["value"])

Unless it's required to be able reset the instance's attributes, I'd set them inside __init__ and avoid the method call:

class MyClass:

    def __init__(self, configuration):
        for k, v in configuration["parameters"].items():
            setattr(self, k, v["value"])
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
1

I am not entirely sure what you want to do since I don't know what In[] / Out[] means and you don't show your entire code, but I guess you're looking for something like

class MyClass:

    def __init__(self, configuration):
        self.set_parameters(configuration)


    def set_parameters(self, configuration):
        self.__dict__ = {k:v.value for (k,v) in configuration["parameters"].items()}
flyx
  • 35,506
  • 7
  • 89
  • 126