[Tutor] Valid usage of lambda expression

Cameron Simpson cs at cskk.id.au
Tue Sep 28 23:59:19 EDT 2021


On 29Sep2021 05:50, Manprit Singh <manpritsinghece at gmail.com> wrote:
>Suppose i have to make 3 functions in a program
>1) sqr for returning square of a number
>2) cube for returning cube of a number
>3) cuberoot for getting cube root of a number
>
>Now if  start with a function definition  like this :
>def make_powerfunction(n):
>     return lambda x: x**n
>
>and then :
>square = make_powerfunction(2)
>cube = make_powerfunction(3)
>cuberoot = make_powerfunction(1/3)
>
>and then doing some maths
>>>> square(3)
>9
>>>> cube(4)
>64
>>>> cuberoot(27)
>3.0
>
>My question is, is it a good practice to derive new functions in this way,
>as i have derived the functions square, cube and cuberoot from
>make_powerfunction.

Seems fine to me, given the situation described.

What you're doing is essentially currying: providing a more complex 
function with some of its parameters prefilled:

    https://en.wikipedia.org/wiki/Currying

You can do this in a few ways in Python. Your method is one, using a 
closure to provide "n" from the scope where you defined the function 
(lambda).  There is also the "partial" function from the functools 
module. You could also define a callabe class (one with a __call__ 
method) and prefill instances with some of the function parameters.

Once again, good practice in Python is often pragmatic: is your 
implemenetation concise and readable and efficient? Then it is probably 
good practice.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list