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.
Related concepts
→
with Statements
→
- Flask extensions
- Flask-WTF
- Python: Installing Python
- Python: Installing Python packages
- Django
- Django migrations
- Django testing
- Test client
- Manager
- Django forms: Building a form
- Django templates: Configuration
- Generic views
- Django model: Search in models
- Django model: Handle transactions
- Django model: Database instrumentation
- Django URL dispatcher: Path converters
- render()
- get_object_or_404()
- tuple
- set
- dictionary
- Virtual Environment: Creating Virtual Environment
- continue Statements
- filter()