Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing defs with lambda expressions python 3.3

i'm new to programming but im stuck with a question, which im asking myself. I made an example like this:

u = 1

def method1(x):
    def method2(n):
        def method3(m):
            return x + n + m
        def method4():
            global u
            u += 1
        method4()
        return method3
    def method5(y):
        return x + y
    return method2, method5

The question is: Can I replace some of these defintions with lambda expressions? I dont want to change the semantics of the code above. I was thinking about something like this:

u = 1
def method1(x):
    def method2(n):
        lambda m: x + n + m
        def method4():
            global u
            u += 1
        method4()
    lambda y: x + y
    return method2

If this what i have done is correct, can i replace even more definitions without changing the semantics of the code or am I wrong?

like image 553
Iduens Avatar asked Sep 06 '26 09:09

Iduens


1 Answers

It is not completely correct since you do not store the lambda expressions nor do you return them. A semantically equivalent program should be:

u = 1

def method1(x):
    def method2(n):
        method3 = lambda m: x + n + m
        def method4():
            global u
            u += 1
        method4()
        return method3
    method5 = lambda y: x + y
    return method2, method5

can i replace even more definitions without changing the semantics

I think unless you make the program totally unreadable, this is about it. Mind however that you do not have to transform all functions into lambda expressions: it is simply useful and can sometimes improve readability. But it should not be a goal by itself.

Note: like @juanpa.arrivillaga says it is however not recommended to store lambda expressions into variables, etc. It is against style guidelines. It is not semantically incorrect, but is not considered good coding.

like image 149
Willem Van Onsem Avatar answered Sep 07 '26 23:09

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!