python contextlib

Creator
Creator
Seonglae Cho
Created
Created
2021 May 31 7:4
Editor
Edited
Edited
2024 May 22 3:53
Refs

with block

  1. File operations: Automatically closing files after use.
  1. Thread and process locking: Acquiring and releasing locks.
  1. Database connections: Connecting to and disconnecting from databases.
  1. Temporary environments: Creating and cleaning up temporary environments.
  1. Logging: Temporarily changing logging levels.
  1. Timing operations: Measuring the execution time of a block of code.

How
Python with

  • __enter__
  • __exit__
python contextlib Class
 
from contextlib import contextmanager import time @contextmanager deftimer(label): start = time.time() try: yield finally: end = time.time() print(f'{label}: {end - start} seconds') # Usage: with timer('Model training'): # Your code block here, e.g.: # train your model
 
 
 
 

Recommendations