You can iterate over list, dict, string, file. All these are iterable! Means you can loop around them and read your data. All iterables support iter() for x in obj: # some statement -------------- _iter = iter(obj) while 1: try: x = _iter.__next__() except StopIteration: # No more items break Behind Cover: How it works?
Instead of returning a single value, each time it generates value using the yield statement. When you call your generator function, it creates a generator object
• You can now easily write your own iterator • Unlike iterator, generator can be iterated only once. • Yield keyword should be used in function • Generator function starts to yield value as your loop starts to run. When the for loop starts to run, generator function will run till first yield statement and return the value and as it continues it runs each time till yield. • Performs better when you have large data set. • When Generator returns, iteration stops (using conditions)
web-log, each line look like: 125.25.238.64 - - [24/Feb/2008:01:04:49 -0600] "GET /ply/bookplug.gif HTTP/1.1" 200 12382 • At any point in code, it didn’t load any temp data to memory. • Here is a sample of code, where the total bytes transferred in requests across a log is summed up.. • This can be extended to use case to filter out log based on error codes, grep for pattern and so on..
Yield expression not only generates value but can receive values and act on it Can be used for listening events, publish/subscription models. def receiver(): while True: item = yield print('Got:', item) rec = receiver() next(rec) # Move to Yield rec.send(‘Hi’) >>> Got: Hi rec.send(‘Hello’) >>> Got: Hello
functions. They are wrappers that allow to execute code before and after the function they decorate without modifying the actual function. In python, functions are Objects. This can help you understand how decorators work. As functions are Objects, it can be assigned. As functions are Objects, we can create function inside function. As functions are Objects, we can pass function inside function As functions are Objects, we can return function inside function.
The most commonly used Context Manager is ‘With’ statement. It helps to avoid lot of boiler plate codes. You need not worry about open and closing the file. Context Managers handle them.