functools.partial — Smart alternative to lambda
Recently I was browsing through the recipes of Python decorators when I came across a rather interesting function.
It spurred me up because to be very honest I have never seen how it works or what it does.
Below I have tried to explain partial by means of a code example and a link to the best answer I found on the internet.
>> def convert_to_int(some_value, int_base):
return int(some_value, base=int_base)
>> convert_to_int("1010", 2)
>> convert_to_int("1010", 8)
>> convert_to_int("1010", 10)
>> from functools import partial
>> str2bin = partial(convert_to_int, int_base=2)
>> str2oct = partial(convert_to_int, int_base=8)
>> str2dec = partial(convert_to_int, int_base=10)
So it must be pretty how and what partial does, but why?
This is one amazing part that the creators of Python share on stackoverflow.com
While the best response and explanation about partial is as mentioned here.
PS: Happy coding!
Originally published at datqaguy.wordpress.com on August 20, 2015.