I'm often confused by recent obsession of generators in python. I'll try to explain them as simply as possible. Say you have never used iterators but coded in python. BUT I'm sure you have used dictionaries (dict) and have met requirement to iterate through it's keys and/or values. TADA! You have used generators already ;).
So generator is a function in python. Except for it uses a keyword yield in it's code. Thus making it the iterator. So you could call this function in a sequence like you would probably do iterating over a dictionary already. E.g.:
So this function returns an iterator generator like the dict() type has by default. And has a next() function, like usual iterators have.
So in attempt to using human language:
Generators are simple functions converted to iterators.
So when a generator function calls it's magic word yield, the "state" of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded.
So. that was the theory. Better to look at example well commented out:
Output will be like:
That's probably all the magic about the generators. Best way to get it is to open your console. NOW! And try to do it yourself.
Comments?
So generator is a function in python. Except for it uses a keyword yield in it's code. Thus making it the iterator. So you could call this function in a sequence like you would probably do iterating over a dictionary already. E.g.:
# typical iteration through dictionary key: value set for key, value in dict.iteritems(): # do someth # Usage of your own iterator for item in iterator_functuon(): # do something with function generated output
So in attempt to using human language:
Generators are simple functions converted to iterators.
So when a generator function calls it's magic word yield, the "state" of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded.
So. that was the theory. Better to look at example well commented out:
def gen_odd_nums(): # executed once (first call) usually like __init__() of a generator odd_num = 1 while True: # saves context and return from function yield odd_num odd_num = odd_num + 2 # Typical generator usage generator_object = gen_odd_nums() # initialising a generator once for i in range(5): # calls generator_object.__next__() print next(generator_object)
1 3 5 7 9
Comments?
Comments
Post a Comment