37
loading...
This website collects cookies to deliver better user experience
with
statement in Python is often only used when dealing with file operations. Below is an example to read and write a file with Python's built-in open function.with open('hello.txt', 'w+') as f:
data = f.read()
f.write('Hello Python!')
with
statement allows us to reduce code duplicationwith
statement or context manager good for you ask?session.close()
every time we are done with our database transaction in sqlalchemy
. Nor is there anything wrong with having to call the built-in close method every single time we are done reading and writing a file. For that matter, here’s an example of one of these methods:# Poor Example
# ------------
f = open('hello.txt', 'w')
f.write('Hello Python!')
f.close()
with
statement is generally recommended. Using with
statements help you to write more expressive code while avoiding resource leaks.# Good Example
# ------------
with open('hello.txt', 'w') as f:
f.write('Hello Python!')
__init__
__enter__
__exit__
open
function.class CustomFileHandlerContextManager:
"""
A custom context manager used for handling file operations
"""
def __init__(self, filename, mode):
print('__init__ method is called.')
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
print('__enter__ method is called.')
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
print('__exit__ method is called.')
self.file.close() # NOTE: So that we can use `CustomFileHandlerContextManager('hello.txt', 'w') as f`
def main():
with CustomFileHandlerContextManager('hello.txt', 'w') as f: # __init__ and __enter__ is called
f.write('Hello! I am not Tom!')
print('Do something else in the statement body.')
# __exit__ is called upon exception or end of the `with` statement
assert f.closed is True # Proof that the file is closed :)
if __name__ == '__main__':
main()
# Output:
# __init__ method is called.
# __enter__ method is called.
# Do something else in the statement body.
# __exit__ method is called.
contextlib
provides us a set of utilities for common operations involving the with
statements.contextlib
, we can omit writing a Python class along with the required Dunder methods for our custom context managers.import contextlib
@contextlib.contextmanager
def custom_file_handler(file_name, file_mode):
file = open(file_name, file_mode)
yield file # NOTE: So that we can use `custom_file_handler('hello.txt', 'w') as f`
file.close() # Anything after yield will act is if it's in the __exit__
def main():
with custom_file_handler('test.txt', 'w') as f:
f.write('Hello, I am Jerry! This is a generator example.')
print('Do something else in the statement body.')
assert f.closed is True # Proof that the file is closed :)
if __name__ == '__main__':
main()
from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://jerry:nsh@localhost/')
Session = sessionmaker(engine)
session = Session()
try:
session.add(some_object)
session.add(some_other_object)
except ProgrammingError as e:
logger.exception(e)
session.rollback()
raise
else:
session.commit()
session.rollback()
and session.commit()
every single time across numerous functions, we can instead use the built-in session as a context manager.sessionmaker
:from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://jerry:nsh@localhost/')
db_session = sessionmaker(engine)
# We can now construct a session which includes begin(), commit(), rollback() all at once
with db_session.begin() as session:
session.add(some_object)
session.add(some_other_object)
# Commits the transaction, closes the session auto-magically! Cool!
with
statement here makes our code look much, much cleaner.with
statement helps to encapsulate the standard use of try
, finally
, else
when it comes to exception handling.