[Python!] - Lazy evaluation

xxhaileypark·2021년 11월 14일
0

Python!

목록 보기
10/11
post-thumbnail

Lazy evaluation

Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (From Wikipedia). It’s usually being considered as a strategy to optimize your code.

Let’s turn this theory into an example. For example, you have a simple expression sum = 1 + 2, Python would try to understand the real meaning of this expression and get the conclusion that sum = 3. This process is called Evaluation and it needs some sort of computation power. In this case, the evaluation is done immediately, therefore it has another name: Strict Evaluation.

On the other hand, we have a non-strict evaluation which is called Lazy Evaluation. The difference is that Lazy Evaluation will not immediately evaluate the expression but only does it when the outcome is needed. It’s a bit like a lazy student who only does the homework when it needs to be submitted to the teacher.

But being lazy here is not necessarily a bad thing, it can improve the efficiency of your code and save plenty of resources. Luckily, Python has silently applied Lazy Evaluation to many built-in functions in order to optimize your code. And I’m sure that you must be familiar with those functions even without being aware of Lazy Evaluation.

[List comprehension & Generator]


list = [sleep_func(x) for x in xrange(5)]

for i in list:
	print i



gen = (sleep_func(x) for x in xrange(5))

for i in gen:
	print i




<결과>

sleep...
sleep...
sleep...
sleep...
sleep...
0
1
2
3
4


sleep...
0
sleep...
1
sleep...
2
sleep...
3
sleep...
4

If you look at the result above, you will see what the difference is if you use a generator. In the case of list, when performing list comprehension, since all values of the list are executed first, the sleep_func() function is executed as much as xrange() value at once. If the execution time in sleep_func() is long or the list value is very large, it becomes a burden the first time it is executed.

However, in the case of a generator, when creating a generator, the actual value is not loaded, and when the for statement is executed, sleep_func() is executed one by one and the value is loaded. The feature is that it can delay long-running operations until the moment it is needed.

Using these features, you can write code for tasks such as fibonacci sequences very efficiently with a concise syntax.

def fibonacci_func(n):
	a,b = 0, 1
	i = 0
	while True:
		if (i > n):   return 
        yield a
	a, b = b, a+b	
        i += 1
        

fib = fibonacci_func(10)

for x in fib:
print x

출처: https://bluese05.tistory.com/56 [ㅍㅍㅋㄷ]

Resource
https://towardsdatascience.com/what-is-lazy-evaluation-in-python-9efb1d3bfed0

https://bluese05.tistory.com/56

profile
I'm a deeply superficial person.

0개의 댓글