Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example where lambdas are very useful in Python

I met lambda expressions in Python. I have seen already many easy examples (including examples on SE) where lambda expressions produce functions like adders of whatever but I can't see the real usefulness of them yet, e.g. some example where it would be pain to write the same peace of code without lambdas.

Could you show something for text processing where you would use lambda expressions and it would be hard to avoid lambda expressions? But something that is practical (not mathematical game).

like image 230
xralf Avatar asked Dec 16 '22 06:12

xralf


1 Answers

IN this case, it would have been painful to write out all lambda expressions as separate function.

What does this code does in briefly? Converts a custom excel table into insert statements for a custom database table. There is mapping between the excel table fields and the database fields and also there is a mapping between excel table fields and functions to be applied on the excel table value, before it gets inserted to the db. You do not really want to define a separate function for every field.

map_func = { 'ID' : lambda x : 'mig_farm_seq.nextval',
             'ENTERPRISE_NAME' : wrap_str,
             'TAX_NUMBER' : wrap_str,
             'FAMILY_NAME' : lambda x : wrap_str(x.split()[0]),
             'GIVEN_NAME' : lambda x : wrap_str(x.split()[1]),
             'ENTERPRISE_REGISTRATION_NUMBER' : wrap_str,
             'PREMISE_NAME' : wrap_str,
             'HOUSE_ID' : wrap_str,
             'POSTAL_CODE' : wrap_str,
             'PHONE_NUMBER_1' : lambda x : wrap_str(get_phone_number(x, True)),
             'PHONE_NUMBER_2' : lambda x : wrap_str(get_phone_number(x, False)),
             'FAX_NUMBER' : lambda x : wrap_str(x.replace(' ', '')),
             'BANK_IDENTIFIER' : lambda x : wrap_str(x.replace(' ', '').replace('-', '')[:3]),
             'BANK_ACCOUNT_NUMBER' : lambda x : wrap_str(x.replace(' ', '').replace('-', '')),
             'NUMBER_OF_EMPLOYEES' : wrap_null,
             'SETTLEMENT_NUMBER' : wrap_null,
             'REGISTRATION_NUMBER' : lambda x : insert_reg_number % x,
             'GENDER' : wrap_str,
             'ACTIVITY' : lambda x : '0',
             'REG_HOLDER_ACTIVITY' : lambda x : '0',
             'PROCESSED_BY_JOB' : lambda x : '0'
         }

source: http://pastebin.com/MxEPBMaZ

like image 168
bpgergo Avatar answered Dec 27 '22 18:12

bpgergo