Hi,
I'm relatively new to Python and would like to know if I'm reinventing a wheel or do things in a non-pythonic way - read wrong.
I'm rewriting some parser originally written in Lua. There is one function which accepts a field name from imported table and its value, does some actions on value and stores it in target dictionary under a appropriate key name.
In the original code it's solved by long switch-like statement with anonymous functions as actions. Python code looks like the following:
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()
...
Every "field-handler" function does different actions and stores in different keys in target_dict, of course. Because Python does not support anonymous functions with statements (or did I missed something ?) the functions have to be written separately which does code less readable and unnecessarily complicated.
Any hints how to do such tasks in a more elegant and more pythonic way are appreciated.
Thx
David