diff --git a/Doc/library/shelve.rst b/Doc/library/shelve.rst --- a/Doc/library/shelve.rst +++ b/Doc/library/shelve.rst @@ -39,18 +39,24 @@ lots of shared sub-objects. The keys a vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated). .. note:: Do not rely on the shelf being closed automatically; always call - :meth:`close` explicitly when you don't need it any more, or use a - :keyword:`with` statement with :func:`contextlib.closing`. + :meth:`~Shelf.close` explicitly when you don't need it any more, or + use a :keyword:`with` statement with :func:`contextlib.closing`. + + Starting with Python 3.4, you can use :func:`shelve.open` as a + context manager via the :keyword:`with` statement:: + + with shelve.open('spam') as db: + db['eggs'] = 'eggs' .. warning:: Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure to load a shelf from an untrusted source. Like with pickle, loading a shelf can execute arbitrary code. Shelf objects support all methods supported by dictionaries. This eases the @@ -113,20 +119,26 @@ Restrictions If the *writeback* parameter is ``True``, the object will hold a cache of all entries accessed and write them back to the *dict* at sync and close times. This allows natural operations on mutable entries, but can consume much more memory and make sync and close take a long time. The *keyencoding* parameter is the encoding used to encode keys before they are used with the underlying dict. + :class:`~Shelf` objects are supported as context managers via the + :keyword:`with` statement. + .. versionadded:: 3.2 The *keyencoding* parameter; previously, keys were always encoded in UTF-8. + .. versionchanged:: 3.4 + Added context manager support. + .. class:: BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8') A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`!next`, :meth:`previous`, :meth:`last` and :meth:`set_location` which are available in the third-party :mod:`bsddb` module from `pybsddb `_ but not in other database modules. The *dict* object passed to the constructor must support those