Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The shelve module offers a simple, persistent, dictionary-like interface for storing and retrieving Python objects to and from disk. While convenient for basic local persistence, it is built directly on top of the pickle module and inherits all of its serious security risks.

Security Concerns

The shelve module uses pickle for both serialization (shelve.sync(), object storage) and deserialization (shelve.open() and item retrieval). This means that loading data from a shelf file can trigger arbitrary code execution if the file originates from an untrusted source.

Key risks include:

Preventive Measures

Example

Safe usage (trusted local data only):

import shelve

with shelve.open('local_config.db') as db:
    db['user_settings'] = {'theme': 'dark', 'timeout': 30}
    settings = db['user_settings']  # Safe because file is trusted

Dangerous usage (to avoid):

import shelve

# Never do this with files from untrusted sources
with shelve.open('untrusted_data.db') as db:  # Arbitrary code execution possible!
    malicious_data = db['payload']

Discussion

Shelve is only appropriate for fully trusted environments — typically single-user applications where the shelf file is never exposed to external input or third parties. In practice this is near to impossible for most use cases.

The fundamental problem with shelve is that it provides an attractive, high-level interface that hides the dangerous pickle implementation underneath. Developers often underestimate the risk because the API feels like a simple dictionary.

Unlike pickle used directly, shelve adds the complication of persistent files that may be tampered with over time or replaced by attackers. This makes it especially dangerous in desktop applications, plugins, or any scenario where files can be swapped.

Modern Python security guidance strongly recommends avoiding pickle-based solutions for anything beyond fully controlled, internal use cases. The convenience of shelve rarely outweighs the long-term maintenance and security burden it introduces.

More Information