with Statements

with Statements — is used in exception handling to make the code cleaner and much more readable.

with Statements — context managers.

# 1) without using with statement 
file = open('file_path', 'w') 
file.write('hello world !') 
file.close() 
  
# 2) without using with statement 
file = open('file_path', 'w') 
try: 
    file.write('hello world') 
finally: 
    file.close() 
class MessageWriter(object): 
    def __init__(self, file_name): 
        self.file_name = file_name 
      
    def __enter__(self): 
        self.file = open(self.file_name, 'w') 
        return self.file
  
    def __exit__(self): 
        self.file.close() 
  
# using with statement with MessageWriter 
  
with MessageWriter('my_file.txt') as xfile: 
    xfile.write('hello world') 

simplifies the management of common resources like file streams.

to create it you need to implement the methods __enter__() and __exit__() in the object methods.

with Statements — Structure map

Clickable & Draggable!

with Statements — Related pages: