Dictionary-dependent operator with actions

I am relatively new to Python and would like to know if I reinvent the wheel or do things in a non-neat way - read it wrong.

I am rewriting the parser originally written in Lua. There is one function that takes a field name from an imported table and its value, performs some actions by value and stores it in the target dictionary under the corresponding key name.

In the source code, it was resolved with a long key, similar to an operator, with anonymous functions as actions. Python code is as follows:

class TransformTable:
    target_dict = {}
    ...
    def mapfield(self, fieldname, value):
        try:
            {
                'productid': self.fn_prodid,
                'name': self.fn_name,
                'description': self.fn_desc,
                ...
            }[fieldname](value)
        except KeyError:
            sys.stderr.write('Unknown key !\n')

    def fn_name(val):
        validity_check(val)
        target_dict['Product'] = val.strip().capitalize()
    ...

" " target_dict, . Python ( - ?), , .

, , .

+5
2

, @Matti Virkkunen'a , "switch case python , ". . , :

class TransformTable:
    target_dict = {}

    def productid(self, value):
        ...
    def name(self, value):
        validity_check(value)
        self.target_dict['Product'] = value.strip().capitalize()
    def description(self, value):
        ...

    def _default(self, value):
        sys.stderr.write('Unknown key!\n')

    def __call__(self, fieldname, value):
        getattr(self, fieldname, self._default)(value)

transformtable = TransformTable() # create callable instance

transformtable(fieldname, value) # use it
0

, - - :

getattr(self, "fn_" + fieldname)(value)

: hasattr, , , KeyError. AttributeError. , try..except , KeyError, , .

+1

All Articles