Don’t worry if it doesn’t work right. If everything did, you’d be out of a job. (Mosher’s Law of Software Engineering)
The context managers allow to allocate and release resources precisely when a program wants to get access to a resource on the computer. It asks the OS for it and the OS provides it with a handle for that resource requested. Some common examples of such resources are files and network ports. Whenever we open a resource, we have to remember to close it, so that the resource is freed. But unfortunately, it’s easier said than done in the program. The with
statement is a widely used example of context managers.
--------------------------------------------------------------
## Manually managing the resources
f = open('test.txt','r')
file = f.read()
f.close()
--------------------------------------------------------------
## Using with statement to manage the resources automatically
with open('test.txt','r') as f:
file = f.read()
--------------------------------------------------------------
This context managers can also be used in threads where we are manually acquiring and releasing locks, opening and closing the database connections manually so that the OS manages automatically for us.
#programming #software-development #python-programming #software-engineering #python