Function - replacing defs with lambda expressions python 3.3

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

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.

https://www.python.org/dev/peps/pep-0008/#programming-recommendations https://www.python.org/dev/peps/pep-0008/#programming-recommendations

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/41752060/replacing-defs-with-lambda-expressions-python-3-3

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils