(any)dbm module lacks a context manager
nick.cash at npcinternational.com
Thu Jan 31 20:34:16 CET 2013
> >>> import dbm
> >>> with dbm.open("mydb", 'c') as d:
> ... d["hello"] = "world"
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: '_dbm.dbm' object has no attribute '__exit__'
This error message is somewhat misleading... it actually means you're trying to use an object as a context manager, and it doesn't implement the context manager protocol (defined __enter__ and __exit__ methods). In this case, db.open() returns a dict -like object that is not a context manager. You'd need to refactor your code to something like:
d = dbm.open("mydb", 'c')
d["hello"] = "world"
You may want to wrap any actions on d with a try-except-finally so you can always close the db. If dbm objects were real context managers, they would do this for you.
This does seem like a useful enhancement. It might be slightly involved to do, as the dbm module has multiple implementations depending on what libraries are available on the OS.
More information about the Python-list