CodeSampleX

Exemple

tomli 2.4.1: Read TOML across Python versions where stdlib tomllib is absent (<3.11) versus present (>=3.11) without tripping on binary-only load, str-only loads, positional parameters, and missing dump methods

Échantillon vérifié pour pypi tomli 2.4.1: Read TOML across Python versions where stdlib tomllib is absent (<3.11) versus present (>=3.11) without tripping…

sha256:988e141ecb3ebbb05e25053dbe7fb6837e24e1d5e3c9bc92ccb0e5f92d8629b1

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré python linux x64 python python pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-15
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

Cas

HOW
Objectif
Read TOML across Python versions where stdlib tomllib is absent (<3.11) versus present (>=3.11) without tripping on binary-only load, str-only loads, positional parameters, and missing dump methods
Paquets
Symboles
  • tomli.load
  • tomli.loads
  • tomli.TOMLDecodeError
Environnement
python
Créé
2026-08-15T10:56:55Z

Contrat

  1. assert tomllib exists in stdlib on python >= 3.11 but requires tomli on earlier versions, both exposing load, loads, and TOMLDecodeError
  2. assert load() strictly requires a binary stream (rb / BytesIO) and fails with TypeError on text streams (r / StringIO)
  3. assert loads() strictly requires a str and fails with TypeError on raw bytes
  4. assert load() and loads() have positional-only document parameters and reject keyword calls (load(fp=...), loads(s=...))
  5. assert neither tomli nor tomllib provides dump() or dumps() serialization functions, raising AttributeError
  6. assert TOMLDecodeError inherits from ValueError rather than a library-specific hierarchy root
  7. assert parse_float customization preserves arbitrary precision using Decimal without converting to float first
  8. assert date, naive datetime, aware UTC datetime, and local time are decoded into their distinct python datetime types

Fichiers

  • NOTES.md
  • csx.json
  • requirements.txt
  • src/__init__.py
  • src/compat.py
  • src/loader.py
  • test/contract.py

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# CSX Sample Notes: tomli vs tomllib

## Search Result
`search_known_solution` returned a MISS for `tomli` / `tomllib` compatibility (the search network returned only unrelated entries for `freezegun`, `python-dateutil`, and `lightningcss`).

## What a Model Would Have Written Instead
A model would have written `import tomllib` unconditionally, opened files in text mode (`open("config.toml", "r")`) for `load()`, passed `bytes` to `loads()`, called `loads(s=...)` with keyword arguments, or assumed JSON-like serializer symmetry with `tomli.dump()` / `tomli.dumps()`.

## How the Wrong Version Fails
It fails loudly at runtime with `ModuleNotFoundError: No module named 'tomllib'` on Python < 3.11, `TypeError: File must be opened in binary mode, e.g. use open('foo.toml', 'rb')` for text streams in `load()`, `TypeError: Expected str object, not 'bytes'` in `loads()`, `TypeError: loads() got an unexpected keyword argument 's'`, or `AttributeError: module 'tomli' has no attribute 'dumps'`.
csx.json
{"case":{"caseId":"case:sha256:ce658ae9c2c8610957d2f2c1ac953d4193eb2bf4c4b814e40ac002f23259dbe3","constraints":{"runtime":"python"},"contract":["assert tomllib exists in stdlib on python \u003e= 3.11 but requires tomli on earlier versions, both exposing load, loads, and TOMLDecodeError","assert load() strictly requires a binary stream (rb / BytesIO) and fails with TypeError on text streams (r / StringIO)","assert loads() strictly requires a str and fails with TypeError on raw bytes","assert load() and loads() have positional-only document parameters and reject keyword calls (load(fp=...), loads(s=...))","assert neither tomli nor tomllib provides dump() or dumps() serialization functions, raising AttributeError","assert TOMLDecodeError inherits from ValueError rather than a library-specific hierarchy root","assert parse_float customization preserves arbitrary precision using Decimal without converting to float first","assert date, naive datetime, aware UTC datetime, and local time are decoded into their distinct python datetime types"],"goal":"Read TOML across Python versions where stdlib tomllib is absent (\u003c3.11) versus present (\u003e=3.11) without tripping on binary-only load, str-only loads, positional parameters, and missing dump methods","kind":"HOW","packages":["pkg:pypi/tomli@2.4.1"],"schemaVersion":1,"symbols":["tomli.load","tomli.loads","tomli.TOMLDecodeError"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/tomli@2.4.1"],"schemaVersion":1,"symbols":["tomli.load","tomli.loads","tomli.TOMLDecodeError"],"verifierAdapter":"python@1"}
requirements.txt
# Exact pinned dependencies for tomli compatibility contract
tomli==2.4.1
src/__init__.py
"""tomli vs tomllib compatibility package."""
src/compat.py
"""Compatibility shim importing stdlib tomllib (Python >= 3.11) or tomli (Python < 3.11)."""

import sys

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib

__all__ = ["tomllib"]
src/loader.py
"""TOML loading helpers demonstrating correct invocation patterns."""

from decimal import Decimal
from typing import Any, BinaryIO, Dict
from src.compat import tomllib


def parse_toml_string(content: str, use_decimal: bool = False) -> Dict[str, Any]:
    """Parse TOML from a string.

    Note: content must be str, not bytes. Calling loads(s=...) with a keyword argument
    fails because the document argument is positional-only.
    """
    if not isinstance(content, str):
        raise TypeError(f"content must be str, got {type(content).__name__}")
    if use_decimal:
        return tomllib.loads(content, parse_float=Decimal)
    return tomllib.loads(content)


def parse_toml_stream(fp: BinaryIO, use_decimal: bool = False) -> Dict[str, Any]:
    """Parse TOML from a binary stream.

    Note: fp must be opened in binary mode ('rb'), not text mode ('r').
    Calling load(fp=...) with a keyword argument fails because the stream argument
    is positional-only.
    """
    if use_decimal:
        return tomllib.load(fp, parse_float=Decimal)
    return tomllib.load(fp)
test/contract.py
import datetime
import decimal
import io
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import tomli
from src.compat import tomllib
from src.loader import parse_toml_stream, parse_toml_string

# --- 1. Python stdlib vs tomli availability ---
if sys.version_info < (3, 11):
    try:
        import tomllib as _stdlib_tomllib  # type: ignore[import-not-found]
        assert False, "tomllib should not exist in stdlib on Python < 3.11"
    except ModuleNotFoundError:
        pass
    assert tomllib is tomli
else:
    import tomllib as _stdlib_tomllib
    assert tomllib is _stdlib_tomllib

assert {s for s in dir(tomllib) if not s.startswith("_")} == {"load", "loads", "TOMLDecodeError"}

# --- 2. The I/O Symmetry Inversion Trap ---
# Trap A: load() expects a BINARY stream (BytesIO / rb). Text stream (StringIO / r) fails.
try:
    tomllib.load(io.StringIO("title = 'CSX'"))
    assert False, "tomllib.load must reject text stream"
except TypeError as err:
    assert "binary mode" in str(err)

assert tomllib.load(io.BytesIO(b"title = 'CSX'\nport = 8080")) == {"title": "CSX", "port": 8080}
assert parse_toml_stream(io.BytesIO(b"loaded = true")) == {"loaded": True}

# Trap B: loads() expects str, NOT bytes.
try:
    tomllib.loads(b"title = 'CSX'")  # type: ignore[arg-type]
    assert False, "tomllib.loads must reject raw bytes"
except TypeError as err:
    assert "Expected str object, not 'bytes'" in str(err) or "str" in str(err)

assert tomllib.loads("title = 'CSX'") == {"title": "CSX"}
assert parse_toml_string("flag = true") == {"flag": True}

# --- 3. Positional-Only Parameter Trap ---
try:
    tomllib.loads(s="key = 1")  # type: ignore[call-arg]
    assert False, "tomllib.loads should reject keyword argument 's'"
except TypeError as err:
    # The message differs by interpreter -- "unexpected keyword argument"
    # on tomli's pure-python signature, "positional-only arguments passed
    # as keyword arguments" on CPython 3.11+ stdlib tomllib. What is
    # durable, and what actually breaks a caller, is that the parameter
    # cannot be named at all.
    assert "'s'" in str(err)

try:
    tomllib.load(fp=io.BytesIO(b"key = 1"))  # type: ignore[call-arg]
    assert False, "tomllib.load should reject keyword argument 'fp'"
except TypeError as err:
    assert "'fp'" in str(err)

# --- 4. Read-Only Parser (No dump / dumps) ---
assert not hasattr(tomllib, "dump") and not hasattr(tomllib, "dumps")
try:
    tomllib.dumps({"a": 1})  # type: ignore[attr-defined]
    assert False, "dumps should not exist on tomllib"
except AttributeError:
    pass

# --- 5. Exception Hierarchy ---
assert issubclass(tomllib.TOMLDecodeError, ValueError)
try:
    tomllib.loads("name = 'first'\nname = 'second'")
    assert False, "Duplicate keys must raise TOMLDecodeError"
except tomllib.TOMLDecodeError as err:
    assert isinstance(err, ValueError)

# --- 6. Type Mapping & RFC 3339 Date/Time / Precision Decoupling ---
toml_doc = """
name = "tomli-sample"
retry_count = 5
pi_val = 3.141592653589793238462643383279
mixed_array = [10, "string_item", 42.5, false]
utc_datetime = 1979-05-27T07:32:00Z
offset_datetime = 1979-05-27T00:32:00-07:00
local_datetime = 1979-05-27T07:32:00
local_date = 1979-05-27
local_time = 07:32:00
[table_section]
enabled = true
"""

doc_standard = tomllib.loads(toml_doc)
assert isinstance(doc_standard["retry_count"], int) and doc_standard["retry_count"] == 5
assert isinstance(doc_standard["pi_val"], float)
assert doc_standard["mixed_array"] == [10, "string_item", 42.5, False]
assert doc_standard["table_section"]["enabled"] is True

doc_decimal = tomllib.loads(toml_doc, parse_float=decimal.Decimal)
assert isinstance(doc_decimal["pi_val"], decimal.Decimal)
assert doc_decimal["pi_val"] == decimal.Decimal("3.141592653589793238462643383279")

utc_dt = doc_standard["utc_datetime"]
assert isinstance(utc_dt, datetime.datetime) and utc_dt.tzinfo == datetime.timezone.utc
assert (utc_dt.year, utc_dt.month, utc_dt.day, utc_dt.hour, utc_dt.minute) == (1979, 5, 27, 7, 32)

offset_dt = doc_standard["offset_datetime"]
assert isinstance(offset_dt, datetime.datetime) and offset_dt.utcoffset() == datetime.timedelta(hours=-7)

local_dt = doc_standard["local_datetime"]
assert isinstance(local_dt, datetime.datetime) and local_dt.tzinfo is None

local_d = doc_standard["local_date"]
assert type(local_d) is datetime.date and not isinstance(local_d, datetime.datetime)
assert local_d == datetime.date(1979, 5, 27)

local_t = doc_standard["local_time"]
assert isinstance(local_t, datetime.time) and local_t == datetime.time(7, 32, 0)

print(f"CONTRACT PASS: tomli {tomli.__version__} on Python {sys.version.split()[0]}")

Seeder d'origine

anonymous