Skip to main content

MTG CardDB

PyPI version Python requirement CI License: MIT

MTG CardDB is a local-first Python library for searching Magic: The Gathering card data with ordinary Python set operations.

It builds an indexed SQLite snapshot from Scryfall data. Queries return immutable sets of Oracle IDs, so you can intersect, union, and subtract card pools without writing SQL or contacting a remote service. The database is downloaded and updated explicitly; importing the package and querying an existing database work offline.

Requirements: Python 3.11+ · No third-party runtime dependencies · MIT-licensed code

Install

python -m pip install mtg-carddb

Initialize a local database once (internet access required):

mtg-carddb init

This downloads Scryfall's Default Cards and Oracle Tags exports and supporting reference catalogs, then builds and validates a SQLite snapshot. The initial build can take several minutes. Subsequent queries use the local database.

To refresh it later, run:

mtg-carddb update

update requires an existing compatible database, builds a replacement before activation, and does not silently change the snapshot used by an already-open CardDatabase handle.

See the getting started guide for database paths, custom locations, CLI options, and troubleshooting.

Look up a card by name

For a one-off lookup, CardDB opens the local SQLite snapshot without loading its full card universe or any inverted indexes:

from mtg_carddb import CardDatabase

with CardDatabase.open() as db:
    for card in db.resolve(db.by_name("Sol Ring")):
        print(card.name, card.oracle_id)

by_name() returns a frozenset[str] of Oracle IDs, matching a whole-card name or an individual face name without regard to case. Unknown names return an empty set. The first lookup of a distinct name queries SQLite; up to 256 recent names, including misses, are cached per open database handle for fast repeats. The cache uses least-recently-used eviction. For many distinct names in one session, call db.preload_names() once to load the full in-memory name index and speed up subsequent queries. This is optional and does not change returned results.

For misspelled names, request suggestions explicitly rather than changing the semantics of by_name():

with CardDatabase.open() as db:
    print(db.suggest_names("Sol Rign", limit=3))
    # e.g. ('Sol Ring', ...)

suggest_names() returns an ordered tuple of canonical whole-card or face names, not IDs; use by_name() on a chosen suggestion to retrieve IDs. Suggestions compare names case-insensitively, normalizing common punctuation and whitespace differences. The candidate catalog loads only when suggestions are first requested; exact-name startup and the bounded name cache are unaffected. Poor matches may yield no suggestions.

Existing schema-v1 databases work unchanged; no init or update is required to use the name-lookup or suggestion paths.

Representative printing images

with CardDatabase.open() as db:
    ids = db.by_name("Sol Ring")
    for oracle_id in ids:
        images = db.images_for(oracle_id)
        print(images.front if images else None)
        print(images.back if images else None)

images_for() returns CardImages(front, back) with Scryfall's normal image URLs. Single-sided printings have back=None. Older databases remain readable; they return CardImages(None, None) for known cards until refreshed with an image-capable builder. URLs are stored locally, but image content is not downloaded or cached by CardDB.

The chosen image is a recent ordinary English paper printing when one is available; promotional, Secret Lair, digital-only, and alternate-treatment versions rank lower. For example, this prefers the Innistrad Remastered Delver of Secrets over a newer Secret Lair edition. This is a deterministic local approximation of Scryfall's default display choice, not an exact replication of an undocumented ranking algorithm. If a card has only special printings, those images remain eligible.

Resilient type-line imports

Scryfall bulk records occasionally contain nonstandard type-line separators, missing separators, or novelty/unknown subtype labels. During init and update, CardDB normalizes recognized alternate separators, infers a missing separator only when exactly one split is fully supported by type catalogs, and preserves unfamiliar subtypes verbatim when the separator is explicit. It does not guess unknown card types or autocorrect misspellings. Original Scryfall type-line text remains available on card and face records.

The build result records structured recovery counts and up to twelve examples; mtg-carddb init and update display them when encountered. Truly ambiguous or structurally invalid records still fail validation rather than silently inventing card attributes or omitting cards.

Query cards

from mtg_carddb import CardDatabase

with CardDatabase.open() as db:
    candidates = (
        db.within_identity("BG")
        & db.by_type("Creature")
        & db.by_legality("commander", "legal")
        & db.mana_value_between(2, 5)
    )

    print(f"Found {len(candidates)} cards")

    for card in db.resolve(candidates)[:10]:
        print(card.name, card.mana_value, card.type_line)

Every card search returns a frozenset[str] of Scryfall Oracle UUIDs. Use Python's &, |, -, and ^ operators to combine results; call db.resolve(...) when you need immutable card records. Results are Oracle identities, not individual printings.

Other queries

with CardDatabase.open() as db:
    # Exactly two colors, versus any subset of those colors
    exactly_golgari = db.exact_identity("BG")
    golgari_eligible = db.within_identity("BG")

    # Names, supertypes, and exclusions compose with other searches
    legendary_creatures = db.by_supertype("Legendary") & db.by_type("Creature")
    not_banned = legendary_creatures - db.by_legality("commander", "banned")

    # Historical observations preserve set, rarity, and game together
    paper_rares = db.by_set_rarity("MKM", "rare", game="paper")

    # Discover available Oracle Tag slugs before querying them
    if db.tag_slugs:
        slug = sorted(db.tag_slugs)[0]
        tagged = db.by_tag(slug)  # Includes descendants by default
        direct = db.by_tag(slug, include_descendants=False)

        # Check a single card without loading the global tag index.
        for card_id in db.by_name("Sol Ring"):
            is_tagged = db.has_tag(card_id, slug)
            directly_tagged = db.has_tag(
                card_id, slug, include_ancestors=False
            )

by_tag() expands a requested tag downward to its descendants. has_tag() checks the card's direct tags and, by default, their ancestors; set include_ancestors=False to require direct assignment.

Tags and their hierarchy depend on the installed Scryfall Oracle Tags snapshot. The library reports source legality and card properties; it does not implement deck-construction rules or user-specific bans.

What it supports

  • Fast exact-name lookup and fuzzy suggestions: low-overhead exact searches with a bounded per-handle cache, optional full name-index preloading, and opt-in dependency-free similar-name suggestions.
  • Composable inverted-index searches: color, color identity, card types and subtypes, supertypes, keywords, mana value, produced mana, layouts, and other documented predicates.
  • Oracle Tags: direct classification assignments, descendant expansion, and lightweight single-card has_tag() checks.
  • Legality and printing history: current Scryfall format statuses and historical set/rarity/game observations, without conflating unrelated printings.
  • Multifaced cards: normalized, immutable card and face records, including reversible layouts.
  • Representative art: local Scryfall normal front/back image URLs with ordinary-printing preference; no printing inventory or image downloads.
  • Resilient imports: conservative recovery of known type-line errors with diagnostic counts rather than manual source exceptions.
  • SQLite snapshots: read-only access, explicit initialization/updates, source provenance, and freshness diagnostics.
  • CLI and Python lifecycle APIs: init, update, info, and locks, with optional custom database paths.

CardDB is a mechanical card-data library, not a rules engine, full collection/printing database, or deckbuilder. It does not reconstruct historical Oracle text or dated ban lists. Source exports are not automatically archived for later byte-identical reconstruction.

Documentation

Version 1.3.0 adds representative printing images and catalog-aware, diagnostic type-line recovery. Version 1.2.1 fixed specific Scryfall import anomalies and Windows cleanup; v1.2.0 added fuzzy suggestions and single-card tag membership on top of the fast v1.1 lookup path. The stable 1.x API remains based on SQLite schema v1. Public names, return types, and documented query semantics follow semantic versioning: compatible changes can ship in 1.x, while intentionally incompatible API changes normally require a new major version. Database files have their own schema version and compatibility checks. See the roadmap for future directions.

Development

For a source checkout:

git clone https://github.com/Dooboofloo/mtg-carddb.git
cd mtg-carddb
python -m pip install -e ".[dev]"
python -m pytest -q --disable-socket

CI runs offline tests on Windows, Linux, and macOS with Python 3.11–3.13, and validates wheel and source-distribution installations. Code and releases remain maintainer-reviewed and human-published.

License and attribution

The original library code is released under the MIT License.

Card data comes from Scryfall and remains subject to applicable third-party terms. Magic: The Gathering and related marks belong to Wizards of the Coast. MTG CardDB is not affiliated with or endorsed by Scryfall or Wizards of the Coast.

Metadata

Release files for mtg-carddb 1.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mtg-carddb 1.3.0
File Size Uploaded Provenance Actions
mtg_carddb-1.3.0.tar.gz 175.2 kB With provenance Details for mtg_carddb-1.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mtg-carddb 1.3.0
File Interpreter ABI Platform Actions
mtg_carddb-1.3.0-py3-none-any.whl Python 3 none any Details for mtg_carddb-1.3.0-py3-none-any.whl

Total release size: 256.6 kB

Release files / mtg_carddb-1.3.0.tar.gz

Download URL mtg_carddb-1.3.0.tar.gz
Size 175.2 kB
Tags Source
SHA-256 checksum
How to use checksums
b8adb3b9ef5a50346b60843c3c1a1415d1ae801e9d99bec0f8da1ac9bec14cd8
BLAKE2b-256 checksum
How to use checksums
d847ec17e78200d8afad6a1d9b23cff81f2074d7e57574ac891c743780f42a1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / mtg_carddb-1.3.0-py3-none-any.whl

Download URL mtg_carddb-1.3.0-py3-none-any.whl
Size 81.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7897a42c2da463faaec6c163f197cb7ae6a3688024244d5316449f7dc4a06415
BLAKE2b-256 checksum
How to use checksums
b95076b46f89c8d81e882d6740ad8e61b0c9e1fd7a5842b8dbddccfffbd92121
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for mtg-carddb 1.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mtg_carddb-1.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page