Closed leighton closed 6 years ago
hmm. i'm not sure what you want to achieve. note that iterators and write batches already implement the context manager protocol, meaning they can be used in a with
block.
do you mean that you want to allow a DB
instance to be used as a context manager? i don't see any use case for that...
additionally, i don't code before breakfast. ;)
with plyvel.DB('./_db') as db:
print db.get('key')
__exit__
will close the "connection" and release the lock in the level db directory
Use case: long running processes that infrequently access the database where one wishes to close the connection to avoid contention.
the contextlib
module from the stdlib has a closing()
context manager helper which might help here:
from contextlib import closing
with closing(plyvel.DB('./_db') as db:
print db.get('key')
alternatively you could write a context manager wrapper if you want more flexibility and less repetition in your code (e.g. no repeated db names). easiest way is to use contextlib
again:
from contextlib import contextmanager
@contextmanager
def magic_db():
db = plyvel.DB('./_db')
try:
yield db
finally:
db.close()
...which can be used like this:
with magic_db() as db:
db.get(b'foo')
Since we're talking about coding patterns: I often code before breakfast, but I rarely connect to the internet before breakfast.
good pattern.
I would like to use plyvel in a notebook development environment (ipython). Supporting a graceful close (i.e. lock release) between code evaluations using the
__exit__
interface would be great for dynamic evaluation environments. I would make a pull request but I think this change is trivial and you'd have it done before breakfast :)