Lazy evaluation and late python binding?

when is lazy appreciation? (generator, if, iterator?) when late binding? (closure, regular functions?)

    a = [1,2,3,4]
    b = [lambda y: x for x in a] 
    c = (lambda y: x for x in a) #lazy evaluation
    d = map(lambda m: lambda y:m, a) #closure
    for i in b:
        print i(None)
    # 4 4 4 4
    for i in c:
        print i(None)
    # 1 2 3 4 
    for i in d:
        print i(None)
    # 1 2 3 4
+4
source share
1 answer

It looks like homework, so I’m not just giving you the answers. Here are two functions you can perform and see how the values ​​change.

def make_constants_like_generator():
    def make_constant(x):
        def inner(y):
            return x
        return inner
    results = []
    for i in [1, 2, 3, 4]:
        results.append(make_constant(i))
        for f in results:
            print f(None)
    return results

def make_constants_like_list():
    x = None
    results = []
    for i in [1, 2, 3, 4]:
        x = i
        def inner(y)
            return x
        results.append(inner)
        for f in results:
            print f(None)
    return results

Lazy assessment waits until the last possible moment to evaluate the expression. The opposite is an impatient assessment. The generator expression is lazy, it does nothing until it is repeated. The list expression is impatient, as soon as it occurs, the list is filled with values.

, , . python . , , , , , ,

def map(func, iter):
    return (func(val) for val in iter)
+1

Source: https://habr.com/ru/post/1685643/


All Articles