Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of __exit__ interface #44

Closed
leighton opened this issue Jan 26, 2016 · 5 comments
Closed

Implementation of __exit__ interface #44

leighton opened this issue Jan 26, 2016 · 5 comments

Comments

@leighton
Copy link

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 :)

@wbolster
Copy link
Owner

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. ;)

@leighton
Copy link
Author

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.

@wbolster
Copy link
Owner

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')

@tlevine tlevine mentioned this issue Mar 16, 2016
@tlevine
Copy link

tlevine commented Mar 16, 2016

Since we're talking about coding patterns: I often code before breakfast, but I rarely connect to the internet before breakfast.

@geyang
Copy link

geyang commented May 4, 2019

good pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants