Skip to main content

Posts

Showing posts from August, 2017

Python Generators use cases

Hi Friends recently I have been studying generators in python. During my course of study I found few really cool use cases for use of generators. In this post I will be describing few use cases where generators could be useful. Eager Parsing of List Suppose we have a function which does some computation and returns a set of data. In real world scenario we could relate it to a function which does some database operation and returns a list of entry from database. Below is the sample code. # Scenario 1 without generators from time import sleep def load_data: data = list() for i in range(10): data.append(i) sleep(0.5) return data data = load_data() for _ in data: if _ > 5: break print _ Above code calls load_data function, the function above iterates 10 times and in each iteration it sleeps for 0.5 seconds. So total time taken by function is 5 seconds. Now if see our code after the call to load_data we are looping throug