CodeSampleX

Ejemplo

tqdm 4.70.0: iterate with tqdm progress bar and update manually

Muestra verificada para pypi tqdm 4.70.0: iterate with tqdm progress bar and update manually. El contrato se ejecutó en python 3.12 · linux alpine/x64 …

sha256:e1cf7cd0d07251af0a81d40f8423983b2dc0d122bfcd0c534d5ebde52cd42c8b

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-27

Caso

HOW
Objetivo
iterate with tqdm progress bar and update manually
Paquetes
Símbolos
  • tqdm.tqdm
  • tqdm.trange
Creado
2026-08-27T19:08:27Z

Contrato

  1. tqdm(iterable) wraps any sequence and yields all elements in original order
  2. trange(n) iterates over sequence from 0 to n-1 with progress tracking
  3. tqdm(total=N) with update(step) manually increments progress counter pbar.n by step
  4. tqdm context manager automatically closes progress bar upon exit

Archivos

  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/__init__.py
  • src/progress_demo.py
  • test/__init__.py
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: iterate with tqdm progress bar and update manually
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/tqdm@4.70.0
Demonstrate these symbols/APIs:
  - tqdm.tqdm
  - tqdm.trange

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:3e8584c3bf6ab3874a10666b9a6e49d42b2e7cf242eb37676992dde56d9eee6f","contract":["tqdm(iterable) wraps any sequence and yields all elements in original order","trange(n) iterates over sequence from 0 to n-1 with progress tracking","tqdm(total=N) with update(step) manually increments progress counter pbar.n by step","tqdm context manager automatically closes progress bar upon exit"],"goal":"iterate with tqdm progress bar and update manually","kind":"HOW","packages":["pkg:pypi/tqdm@4.70.0"],"schemaVersion":1,"symbols":["tqdm.tqdm","tqdm.trange"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/tqdm@4.70.0"],"schemaVersion":1,"subject":"pkg:pypi/tqdm@4.70.0","symbols":["tqdm.tqdm","tqdm.trange"],"verifierAdapter":"python@1"}
requirements.txt
tqdm==4.70.0
spec.json
{
  "schemaVersion": 1,
  "goal": "iterate with tqdm progress bar and update manually",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/tqdm@4.70.0"
  ],
  "symbols": [
    "tqdm.tqdm",
    "tqdm.trange"
  ]
}
src/__init__.py
src/progress_demo.py
"""Progress bar iteration and manual updating demo using tqdm."""

from typing import Any, Iterable, List
from tqdm import tqdm, trange


def iterate_items(items: Iterable[Any], file: Any = None) -> List[Any]:
    """Iterate over elements with a progress bar and collect results."""
    results = []
    for item in tqdm(items, desc="Processing items", file=file):
        results.append(item)
    return results


def range_loop(count: int, file: Any = None) -> List[int]:
    """Iterate over a numeric range using trange."""
    squares = []
    for i in trange(count, desc="Squaring numbers", file=file):
        squares.append(i * i)
    return squares


def manual_progress_steps(total: int, step_sizes: List[int], file: Any = None) -> int:
    """Manually update a progress bar in steps without an iterable."""
    processed = 0
    with tqdm(total=total, desc="Manual steps", file=file) as pbar:
        for step in step_sizes:
            processed += step
            pbar.update(step)
    return processed
test/__init__.py
test/contract.py
"""Contract test proving tqdm iteration and manual updating."""

import io
import sys
from pathlib import Path

# Add src directory to path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))

from tqdm import tqdm, trange
from progress_demo import iterate_items, range_loop, manual_progress_steps


def test_tqdm_iteration():
    """Verify tqdm wraps iterables and yields all elements in order."""
    sink = io.StringIO()
    data = ["alpha", "beta", "gamma"]
    result = list(tqdm(data, file=sink))
    assert result == ["alpha", "beta", "gamma"], f"Expected {data}, got {result}"

    # Test via wrapper function
    res = iterate_items([10, 20, 30], file=sink)
    assert res == [10, 20, 30], f"Expected [10, 20, 30], got {res}"


def test_trange_iteration():
    """Verify trange iterates from 0 to n-1 matching tqdm(range(n))."""
    sink = io.StringIO()
    result = list(trange(5, file=sink))
    assert result == [0, 1, 2, 3, 4], f"Expected [0..4], got {result}"

    # Test squares via wrapper function
    squares = range_loop(4, file=sink)
    assert squares == [0, 1, 4, 9], f"Expected [0, 1, 4, 9], got {squares}"


def test_manual_update():
    """Verify tqdm manual updates and context manager behavior."""
    sink = io.StringIO()
    total_items = 100

    with tqdm(total=total_items, file=sink) as pbar:
        assert pbar.total == 100
        assert pbar.n == 0

        pbar.update(30)
        assert pbar.n == 30, f"Expected pbar.n=30, got {pbar.n}"

        pbar.update(70)
        assert pbar.n == 100, f"Expected pbar.n=100, got {pbar.n}"

    # Verify manual progress helper
    processed = manual_progress_steps(50, [15, 15, 20], file=sink)
    assert processed == 50, f"Expected 50 processed items, got {processed}"


def main():
    test_tqdm_iteration()
    test_trange_iteration()
    test_manual_update()
    print("All contract assertions passed successfully.")


if __name__ == "__main__":
    main()

Seeder de origen

anónimo