0

I need to create classes dynamically based on parameters parsed from a config file. These classes all need to inherit from the same base class which has a static function for which the implementation differs from one subclass to the other depending on what is found in the config file. To implement the static function I am using a lambda function. But what happens is that the the last implemented lambda function becomes the definition of the static method for all subclasses! How can I make sure to have a different implementation of the static function for each subclass?

Here is a simplification of the code below:

import pandas as pd


class BaseClass():

    @staticmethod
    def static_method(series):
        raise NotImplementedError


if __name__ == '__main__':

    config = {'IntSubClass': {'function': 'isin', 'values': [1, 2, 3, 4, 5]},
              'StrSubClass':  {'function': 'isin', 'values': ['a', 'b', 'c', 'd', 'e']},
              }

    int_series = pd.Series([None, 1, 5])
    str_series = pd.Series([None, 'a', 'd'])

    custom_type_classes = []

    for custom_type_name in config:
        custom_type_class = type(custom_type_name,
                                 (BaseClass,),
                                 {'function': config[custom_type_name]['function'],
                                  'values': config[custom_type_name]['values'],
                                  })

        lambda_function = staticmethod(lambda s: getattr(s.dropna(), getattr(custom_type_class, 'function'))(getattr(custom_type_class, 'values')))

        setattr(custom_type_class, 'static_method', lambda_function)

        custom_type_classes.append(custom_type_class)

        print(custom_type_name)
        print('int_series')
        print(custom_type_class.static_method(int_series), end='\n \n')
        print('str_series')
        print(custom_type_class.static_method(str_series))
        print('----------------------------')


    for item in custom_type_classes:
        print(item)
        print('int_series')
        print(item.static_method(int_series), end='\n \n')
        print('str_series')
        print(item.static_method(str_series))
        print('----------------------------')



0 Answers0