lundi 18 décembre 2017

Detecting Duplicates in Class Instance's Variable Values

class Translator(object):
    def __init__(self, tracking_col='tracking_id', coding_col='coding', qualifying_code_col='qualifying_code',
                 translation_col='translation'):
        self._results = []
        self.tracking_col = tracking_col
        self.data_col = coding_col
        self.definition_col = qualifying_code_col
        self.translation_col = translation_col
        self.__validate_parameters(self.__dict__)

    def __validate_parameters(self, variable_values):
        class_values = {}
        for key, value in variable_values.items():
            if type(value) is str:
                class_values.setdefault(value, set()).add(key)
        for key, values in class_values.items():
            # If there is more than one value, there is a duplicate
            if len(values) > 1:
                raise Exception('Duplicate column names exist in parameters. \'{}\' are set to \'{}\'. '
                                'Do not use duplicate column names.'.format(values, key))

This class cannot have the duplicate values for any of the 'col' variables. If duplicate values exist, logic further in the class may not crash but will create unpredictable results.

Upon instantiation my function __validate_parameters will detect duplicate values and raise an Exception. The problem is I am dumping all the values out to a dictionary, iterating to create another dictionary, and finally manually raising an exception (which from what I've been told is the wrong thing to do in any situation). It's also rather verbose.

Is there a shorter and more concise way to validate for duplicates while propogating an error up without the complexity above?





Aucun commentaire:

Enregistrer un commentaire