Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38010 > unrolled thread

RE: (any)dbm module lacks a context manager

Started byNick Cash <nick.cash@npcinternational.com>
First post2013-01-31 19:34 +0000
Last post2013-01-31 19:34 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  RE: (any)dbm module lacks a context manager Nick Cash <nick.cash@npcinternational.com> - 2013-01-31 19:34 +0000

#38010 — RE: (any)dbm module lacks a context manager

FromNick Cash <nick.cash@npcinternational.com>
Date2013-01-31 19:34 +0000
SubjectRE: (any)dbm module lacks a context manager
Message-ID<mailman.1259.1359664495.2939.python-list@python.org>
> >>> 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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web