Re:Frankenstein's `__init__`
by tayo42 on Saturday April 19, 2025 @05:54PM
(#43739779)
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
[ Parent
| on HN ]
There'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.