Featured Post

Keyword to create root window in python

 (21)CONTEXT MANAGERS:

Context managers are great tool for resource management. they allow you to allocate and release resources precisely when you want to.

for example:

with open('notes.txt''w'as f:
    f.write('some todo...')    

output = creates a notes.txt file and types the txt 'some todo'.



1.Handling exceptions:

You can handle an exception automatically without needing to fix it with code.

for example:

class ManagedFile:
    def __init__(selffilename):
        print('init', filename)
        self.filename = filename

    def __enter__(self):
        print('enter')
        self.file = open(self.filename, 'w')
        return self.file

    def __exit__(selfexc_typeexc_valueexc_traceback):
        if self.file:
            self.file.close()
        if exc_type is not None:
            print('Exception has been handled')
        print('exit')
        return True

with ManagedFile('notes2.txt'as f:
    print('doing stuff...')
    f.write('some todo...')
    f.do_something()
print('continuing...')    

output =                                                

init notes2.txt
enter
doing stuff...
Exception has been handled
exit
continuing...


2.Implementing a context manager as a generator

for example:

from contextlib import contextmanager

@contextmanager

def open_managed_file(filename):
    f = open(filename, 'w')
    try:
        yield f
    finally:
        f.close()
        
with open_managed_file('notes.txt'as f:
    f.write('some todo...')

Comments