Generators, Context-Managers and Coroutines:(Completing course)
- Several Pipelines can be linked together.
- Items flows one by one through the entire Pipeline.
- Pipeline Functionality can be packaged into callable functions.
One Example of Generator pipeline:
for full_name in names:
for name in full_name.split(‘ ‘):
full_names = name.strip() for name in open(‘names.txt’)
names = seprate_names(full_names)
lengths = ((name,len(name))for name in names)
longest = max(lengths,key=lambda x:x)
Another approach is as follows is one wants to use using Function name:
Why we need context-Manager?
‘with’ statement in Python that we use to do file operations is Context-manager. It is something like to “Have the state and open that state and with-in that state to do things”. using with in Python we open file and till the file is open we do some good things and after doing all good things we close the file. So ‘with’ is a context Manager using that we make the state of file open and after that we do all the things we need to do with file.
Other useful cases of Context-manager:
Close/Open File/Socket(Even it crashes)
Commit/Fetch (Even if crashes)
release the lock (Even it crashes)
When you really need Context-Managers?
At last fun not least, If I will be creating a Chat-BOT in Python then I would be able to use Context-Manager in Python so I would be doing some stuff and after completing that stuff I can go out and have fun.
So we use @staticmethod in Python class, that means no matter what happens we will be able to run this method at any cost.
That is just using decorator. Now if we want to create a context manager using decorator?
So what is Context-manager?
- I have to go to a particular directory, list all files with .txt extension, then come-back to current location (Simple use case)
- I have to load specific ML model, I have to predict against several parameters and get results, Return at specific state(un-load the model)
- I have to open Socket connection, Read various kind of data, close Socket connection.
On the other way we can also write it like:
Context-managers are powerful tool to make code more modular and Succinct.
Now What if we have to use Context-manager as Yielded value?
May be little-bit more about COntext-managers-
What are Coroutines and how we have to handle those?
- Receive Values
- May not return anything
- Not for iteration
What is the design of Co-routine:
- Receive Input
- Process that Input
- Stop at yield statement
send() method is used to send value to coroutines.
More uses of Co-routines:
Coroutines are really powerful for Data-Processing Operations.
One of most important course about Co-Routines/Concurrency and really interesting way to handle multiprocessing: http://www.dabeaz.com/coroutines/ —think win win—-