3 ms·
I get the points everyone is making and they make sense, but sometimes you need persistent connections. Open and closing constantly like can cause issues
by tayo42 2y ago
I get the points everyone is making and they make sense, but sometimes you need persistent connections. Open and closing constantly like can cause issues
- mjr00 2y agoThere's nothing about the contextmanager approach that says you're open and closing any more or less frequently than a __init__ approach with a separate `close()` method. You're just statically ensuring 1) the close method gets called, and 2) database operations can only happen on an open connection. (or, notably, a connection that we expect to be open, as something external the system may have closed it in the meantime.) Besides, persistent connections are a bit orthogonal since you should be using a connection pool in practice, which most Python DB libs provide out of the box. In either case, the semantics are the same, open/close becomes lease from/return to pool.