1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
<span id="shelve-python-object-persistence"></span><h1>shelve — Python object persistence</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/shelve.py">Lib/shelve.py</a></p> <p>A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a> module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.</p> <dl class="py function"> <dt class="sig sig-object py" id="shelve.open">
<code>shelve.open(filename, flag='c', protocol=None, writeback=False)</code> </dt> <dd>
<p>Open a persistent dictionary. The filename specified is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created. By default, the underlying database file is opened for reading and writing. The optional <em>flag</em> parameter has the same interpretation as the <em>flag</em> parameter of <a class="reference internal" href="dbm#dbm.open" title="dbm.open"><code>dbm.open()</code></a>.</p> <p>By default, pickles created with <a class="reference internal" href="pickle#pickle.DEFAULT_PROTOCOL" title="pickle.DEFAULT_PROTOCOL"><code>pickle.DEFAULT_PROTOCOL</code></a> are used to serialize values. The version of the pickle protocol can be specified with the <em>protocol</em> parameter.</p> <p>Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written <em>only</em> when assigned to the shelf (see <a class="reference internal" href="#shelve-example"><span class="std std-ref">Example</span></a>). If the optional <em>writeback</em> parameter is set to <code>True</code>, all entries accessed are also cached in memory, and written back on <a class="reference internal" href="#shelve.Shelf.sync" title="shelve.Shelf.sync"><code>sync()</code></a> and <a class="reference internal" href="#shelve.Shelf.close" title="shelve.Shelf.close"><code>close()</code></a>; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume 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).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><a class="reference internal" href="pickle#pickle.DEFAULT_PROTOCOL" title="pickle.DEFAULT_PROTOCOL"><code>pickle.DEFAULT_PROTOCOL</code></a> is now used as the default pickle protocol.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Accepts <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a> for filename.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Do not rely on the shelf being closed automatically; always call <a class="reference internal" href="#shelve.Shelf.close" title="shelve.Shelf.close"><code>close()</code></a> explicitly when you don’t need it any more, or use <a class="reference internal" href="#shelve.open" title="shelve.open"><code>shelve.open()</code></a> as a context manager:</p> <pre data-language="python">with shelve.open('spam') as db:
db['eggs'] = 'eggs'
</pre> </div> </dd>
</dl> <div class="admonition warning" id="shelve-security"> <p class="admonition-title">Warning</p> <p>Because the <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code>shelve</code></a> module is backed by <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a>, it is insecure to load a shelf from an untrusted source. Like with pickle, loading a shelf can execute arbitrary code.</p> </div> <p>Shelf objects support most of methods and operations supported by dictionaries (except copying, constructors and operators <code>|</code> and <code>|=</code>). This eases the transition from dictionary based scripts to those requiring persistent storage.</p> <p>Two additional methods are supported:</p> <dl class="py method"> <dt class="sig sig-object py" id="shelve.Shelf.sync">
<code>Shelf.sync()</code> </dt> <dd>
<p>Write back all entries in the cache if the shelf was opened with <em>writeback</em> set to <a class="reference internal" href="constants#True" title="True"><code>True</code></a>. Also empty the cache and synchronize the persistent dictionary on disk, if feasible. This is called automatically when the shelf is closed with <a class="reference internal" href="#shelve.Shelf.close" title="shelve.Shelf.close"><code>close()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="shelve.Shelf.close">
<code>Shelf.close()</code> </dt> <dd>
<p>Synchronize and close the persistent <em>dict</em> object. Operations on a closed shelf will fail with a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> </dd>
</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://code.activestate.com/recipes/576642/">Persistent dictionary recipe</a> with widely supported storage formats and having the speed of native dictionaries.</p> </div> <section id="restrictions"> <h2>Restrictions</h2> <ul class="simple" id="index-1"> <li>The choice of which database package will be used (such as <a class="reference internal" href="dbm#module-dbm.ndbm" title='dbm.ndbm: The standard "database" interface, based on ndbm. (Unix)'><code>dbm.ndbm</code></a> or <a class="reference internal" href="dbm#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><code>dbm.gnu</code></a>) depends on which interface is available. Therefore it is not safe to open the database directly using <a class="reference internal" href="dbm#module-dbm" title='dbm: Interfaces to various Unix "database" formats.'><code>dbm</code></a>. The database is also (unfortunately) subject to the limitations of <a class="reference internal" href="dbm#module-dbm" title='dbm: Interfaces to various Unix "database" formats.'><code>dbm</code></a>, if it is used — this means that (the pickled representation of) the objects stored in the database should be fairly small, and in rare cases key collisions may cause the database to refuse updates.</li> <li>The <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code>shelve</code></a> module does not support <em>concurrent</em> read/write access to shelved objects. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no other program should have it open for reading or writing. Unix file locking can be used to solve this, but this differs across Unix versions and requires knowledge about the database implementation used.</li> <li>On macOS <a class="reference internal" href="dbm#module-dbm.ndbm" title='dbm.ndbm: The standard "database" interface, based on ndbm. (Unix)'><code>dbm.ndbm</code></a> can silently corrupt the database file on updates, which can cause hard crashes when trying to read from the database.</li> </ul> <dl class="py class"> <dt class="sig sig-object py" id="shelve.Shelf">
<code>class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="collections.abc#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code>collections.abc.MutableMapping</code></a> which stores pickled values in the <em>dict</em> object.</p> <p>By default, pickles created with <a class="reference internal" href="pickle#pickle.DEFAULT_PROTOCOL" title="pickle.DEFAULT_PROTOCOL"><code>pickle.DEFAULT_PROTOCOL</code></a> are used to serialize values. The version of the pickle protocol can be specified with the <em>protocol</em> parameter. See the <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a> documentation for a discussion of the pickle protocols.</p> <p>If the <em>writeback</em> parameter is <code>True</code>, the object will hold a cache of all entries accessed and write them back to the <em>dict</em> 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.</p> <p>The <em>keyencoding</em> parameter is the encoding used to encode keys before they are used with the underlying dict.</p> <p>A <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code>Shelf</code></a> object can also be used as a context manager, in which case it will be automatically closed when the <a class="reference internal" href="../reference/compound_stmts#with"><code>with</code></a> block ends.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Added the <em>keyencoding</em> parameter; previously, keys were always encoded in UTF-8.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Added context manager support.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><a class="reference internal" href="pickle#pickle.DEFAULT_PROTOCOL" title="pickle.DEFAULT_PROTOCOL"><code>pickle.DEFAULT_PROTOCOL</code></a> is now used as the default pickle protocol.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="shelve.BsdDbShelf">
<code>class shelve.BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8')</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code>Shelf</code></a> which exposes <code>first()</code>, <code>next()</code>, <code>previous()</code>, <code>last()</code> and <code>set_location()</code> methods. These are available in the third-party <code>bsddb</code> module from <a class="reference external" href="https://www.jcea.es/programacion/pybsddb.htm">pybsddb</a> but not in other database modules. The <em>dict</em> object passed to the constructor must support those methods. This is generally accomplished by calling one of <code>bsddb.hashopen()</code>, <code>bsddb.btopen()</code> or <code>bsddb.rnopen()</code>. The optional <em>protocol</em>, <em>writeback</em>, and <em>keyencoding</em> parameters have the same interpretation as for the <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code>Shelf</code></a> class.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="shelve.DbfilenameShelf">
<code>class shelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False)</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code>Shelf</code></a> which accepts a <em>filename</em> instead of a dict-like object. The underlying file will be opened using <a class="reference internal" href="dbm#dbm.open" title="dbm.open"><code>dbm.open()</code></a>. By default, the file will be created and opened for both read and write. The optional <em>flag</em> parameter has the same interpretation as for the <a class="reference internal" href="#shelve.open" title="shelve.open"><code>open()</code></a> function. The optional <em>protocol</em> and <em>writeback</em> parameters have the same interpretation as for the <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code>Shelf</code></a> class.</p> </dd>
</dl> </section> <section id="example"> <span id="shelve-example"></span><h2>Example</h2> <p>To summarize the interface (<code>key</code> is a string, <code>data</code> is an arbitrary object):</p> <pre data-language="python">import shelve
d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError
# if no such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = key in d # true if the key exists
klist = list(d.keys()) # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2] # this works as expected, but...
d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!
# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it
# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Module</code> <a class="reference internal" href="dbm#module-dbm" title='dbm: Interfaces to various Unix "database" formats.'><code>dbm</code></a>
</dt>
<dd>
<p>Generic interface to <code>dbm</code>-style databases.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a>
</dt>
<dd>
<p>Object serialization used by <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code>shelve</code></a>.</p> </dd> </dl> </div> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/shelve.html" class="_attribution-link">https://docs.python.org/3.12/library/shelve.html</a>
</p>
</div>
|