(any)dbm module lacks a context manager

Nick Cash nick.cash at npcinternational.com
Thu Jan 31 14:34:16 EST 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:

import dbm
d = dbm.open("mydb", 'c')
d["hello"] = "world"
d.close() 

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.

-Nick Cash




More information about the Python-list mailing list