Skip to content

Instantly share code, notes, and snippets.

@ldipotetjob
Created March 20, 2024 11:39
Show Gist options
  • Save ldipotetjob/a0eeed0f6c4518b54165c0bcec6289bf to your computer and use it in GitHub Desktop.
Save ldipotetjob/a0eeed0f6c4518b54165c0bcec6289bf to your computer and use it in GitHub Desktop.
An example of context managers allocating and releasing resources precisely
# requirement: create the txt file: zen_of_python.txt in the same directory that this python file
filename = 'zen_of_python.txt'
f = open(filename, 'r')
print("1st option 2 print content file")
print(f.read())
f.close()
# two related operations which you’d like to execute as a pair, with a
# block of code in between.
open_file = open(filename, 'r')
with open_file:
print("2nd option 2 print content file")
print(open_file.read())
"""
with EXPRESSION as TARGET:
SUITE
@see: https://docs.python.org/3/reference/compound_stmts.html#the-with-statement
unhandled error
"""
with open(filename) as open_file:
print("3rd option 2 print content file")
"""
for line in open_file:
print(line.rstrip())
"""
print(open_file.read())
# The final solution, handling exceptions
class File(object):
def __init__(self, file_name, method):
try:
self.file_obj = open(file_name, method)
except Exception as e:
print(f"Exception: {e}")
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
if type:
print(f"Exception of type: {type} has been handled: {value}")
self.file_obj.close()
return True
with File('zen_of_python.txt', 'r') as open_file:
# Exception here are managed in File.__exit__
print("4th option 2 print content file")
print(open_file.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment