I'm trying to develop a class that cleans a dictionary based on field types incorporated into the class init function.
Its structure is something like this, but it doesn't work right now, as I can't figure out how to get a variable from the class instance dynamically, and how to apply the function to each variable:
class Cleaner:
def __init__(self):
self.int_fields = ['field_1', 'field_2']
self.float_fields = ['field_3', 'field_4']
self.field_types = [('int_fields', int), ('float_fields', float)]
def get_clean_dict(self, dict):
cleaned_dict = {}
for field_type in self.field_types:
for field_name, transform_func in getattr(self, field_type):
try:
cleaned_dict[field_name] = transform_func(dict.get(field_name))
except Exception:
cleaned_dict[field_name] = None
return cleaned_dict
Here's how I expect it to behave:
sample_dict = {
'field_1': 234,
'field_2': 'Invalid',
'field_3': 45.32345,
'field_4': 'Invalid'
}
cleaner_inst = Cleaner()
cleaned_dict = cleaner_inst.get_clean_dict(sample_dict)
cleaned_dict = {
'field_1': int(234),
'field_2': None,
'field_3': float(45.32345),
'field_4': None
}
__init__, you have to ask yourself: Do I really need a class? To me,Cleanerlooks awfully much like a function...