Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #38010
| From | Nick Cash <nick.cash@npcinternational.com> |
|---|---|
| Subject | RE: (any)dbm module lacks a context manager |
| Date | 2013-01-31 19:34 +0000 |
| References | <20130131130305.40fc78a8@bigbox.christie.dr> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1259.1359664495.2939.python-list@python.org> (permalink) |
> >>> 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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
RE: (any)dbm module lacks a context manager Nick Cash <nick.cash@npcinternational.com> - 2013-01-31 19:34 +0000
csiph-web