dustin
dustin

Reputation: 4406

Python: Using a YAML to auto create class methods

I have been trying to create a bunch of similar methods using a YAML configuration file. However, I have been unable to find something online or figure it out.

example.yml

attributes:
  - a
  - b
  - c

example class

import yaml

class Test:
    def __init__(self):
        with open('example.yml', 'rb') as f:
            attrib_list = yaml.load(f)

        _list = []
        for name in attrib_list:
            _list.append(self.__setattr__('_' + name, None))

# create similar methods in a loop
         for name, _ in zip(attrib_list, _list):
             @property
             def name(self):  # I know name is a string so cannot be this way but how if this can be done?
                 return _

             @name.setter
             def __set + _(self, v):  # __set + '_' + name as method name
                 pass

             @name.getter
             def __get + _(self):  # __get + '_' + name as method name
                 pass

Is there efficient way to create many similar methods this way by looping through a configuration file?

Or is there a better way to handle something of this nature?

Thanks.

Upvotes: 1

Views: 1836

Answers (1)

napuzba
napuzba

Reputation: 6288

Use property class

class Test:
    def __init__(self):
        with open('102.yaml', 'rb') as f:
            attrib_list = yaml.load(f)

        _list = []
        for name in attrib_list['attributes']:
            _list.append(self.__setattr__('_' + name, None))            
            setattr(self.__class__, name, 
               property( Test.getprop(self,name), Test.setprop(self,name)))

    @staticmethod
    def getprop(self,name):
        def xget(self):
            print("Get {}".format(name))
            return name
        return xget

    @staticmethod
    def setprop(self,name):
        def xset(self,value):
            print("Set {} to {}".format(name,value))
        return xset

>>> zz = Test()
>>> zz.a = "hallo"
Set a to hallo
>>> print(zz.a)
Get a
a

Upvotes: 1

Related Questions