CodeSampleX

샘플

packaging 26.2: version.Version, specifiers.SpecifierSet, requirements.Requirement

검증된 샘플 — pypi packaging 26.2: version.Version, specifiers.SpecifierSet, requirements.Requirement. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해…

sha256:429645c8f49885bcc40eaf8d385090fdce1fce1b1dd15e1cc5fd92adc8d858bb

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 python linux 24 · ubuntu · glibc 2.39 x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

케이스

HOW
목표
verify pkg:pypi/packaging@26.2
패키지
심벌
  • packaging.version.Version
  • packaging.specifiers.SpecifierSet
  • packaging.requirements.Requirement
환경
python
생성일
2026-08-20T02:39:45Z

컨트랙트

  1. packaging.version.Version parses semantic version strings and correctly evaluates version ordering precedence
  2. packaging.specifiers.SpecifierSet matches version instances against version specifier constraints and filters candidate lists
  3. packaging.requirements.Requirement parses package dependency requirements with extras and environment markers

파일

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

소스 아티팩트 내려받기 (tar.gz)

소스

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: verify pkg:pypi/packaging@26.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/packaging@26.2

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:b5c906f8e6ced1808568414b5d9bef49d69838554530b1e8b5148564fbfaf789","contract":["packaging.version.Version parses semantic version strings and correctly evaluates version ordering precedence","packaging.specifiers.SpecifierSet matches version instances against version specifier constraints and filters candidate lists","packaging.requirements.Requirement parses package dependency requirements with extras and environment markers"],"goal":"verify pkg:pypi/packaging@26.2","kind":"HOW","packages":["pkg:pypi/packaging@26.2"],"schemaVersion":1,"symbols":["packaging.version.Version","packaging.specifiers.SpecifierSet","packaging.requirements.Requirement"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/packaging@26.2"],"schemaVersion":1,"symbols":["packaging.version.Version","packaging.specifiers.SpecifierSet","packaging.requirements.Requirement"],"verifierAdapter":"python@1"}
requirements.txt
packaging==26.2
sample.py
"""Package versioning and dependency specification utility using packaging."""

from typing import Any
from packaging.version import Version
from packaging.specifiers import SpecifierSet
from packaging.requirements import Requirement


def parse_and_compare_versions(v1: str, v2: str) -> int:
    """Compare two version strings according to PEP 440 ordering.

    Returns:
        -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2.
    """
    ver1 = Version(v1)
    ver2 = Version(v2)
    if ver1 < ver2:
        return -1
    elif ver1 > ver2:
        return 1
    return 0


def filter_compatible_versions(specifier_str: str, candidate_versions: list[str]) -> list[str]:
    """Filter and return candidate versions that satisfy the given specifier expression."""
    spec = SpecifierSet(specifier_str)
    matching = list(spec.filter(candidate_versions))
    return sorted(matching, key=Version)


def evaluate_dependency(
    requirement_str: str,
    installed_version_str: str,
    environment_markers: dict[str, Any] | None = None,
) -> bool:
    """Check if an installed package version satisfies a requirement and its environment markers.

    Returns:
        True if markers match (or no markers) and the version satisfies the specifier;
        False otherwise.
    """
    req = Requirement(requirement_str)
    if req.marker is not None and environment_markers is not None:
        if not req.marker.evaluate(environment_markers):
            return False
    return req.specifier.contains(installed_version_str)


if __name__ == "__main__":
    is_valid = evaluate_dependency(
        "example-pkg>=1.0,<2.0; python_version >= '3.8'",
        "1.5.0",
        {"python_version": "3.11"},
    )
    print(f"Dependency valid: {is_valid}")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/packaging@26.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/packaging@26.2"
  ]
}
test/contract.py
"""Contract verification test for packaging library functionality."""

import os
import sys

# Ensure sample module can be imported from root directory
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from packaging.version import Version
from packaging.specifiers import SpecifierSet
from packaging.requirements import Requirement
from sample import parse_and_compare_versions, filter_compatible_versions, evaluate_dependency


def test_version_parsing_and_ordering():
    """Assertion 1: packaging.version.Version parses semantic version strings and correctly evaluates version ordering precedence."""
    v_base = Version("1.0.0")
    v_pre = Version("1.0.0a1")
    v_post = Version("1.0.0.post1")
    v_dev = Version("1.0.0.dev1")
    v_next = Version("1.0.1")

    assert v_dev < v_pre < v_base < v_post < v_next, "PEP 440 version ordering failed"
    assert v_base.major == 1 and v_base.minor == 0 and v_base.micro == 0
    assert v_pre.is_prerelease is True
    assert v_post.is_postrelease is True
    assert v_dev.is_devrelease is True

    assert parse_and_compare_versions("2.1.0", "2.0.9") == 1
    assert parse_and_compare_versions("1.5.0", "1.5.0") == 0
    assert parse_and_compare_versions("1.0.0b1", "1.0.0") == -1


def test_specifier_matching_and_filtering():
    """Assertion 2: packaging.specifiers.SpecifierSet matches version instances against version specifier constraints and filters candidate lists."""
    spec = SpecifierSet(">=1.5.0, <3.0.0, !=2.0.1")

    assert spec.contains("1.5.0") is True
    assert spec.contains("2.0.0") is True
    assert spec.contains("2.0.1") is False
    assert spec.contains("1.4.9") is False
    assert spec.contains("3.0.0") is False

    candidates = ["1.0.0", "1.5.0", "2.0.0", "2.0.1", "2.5.0", "3.0.0", "3.1.0"]
    compatible = filter_compatible_versions(">=1.5.0, <3.0.0, !=2.0.1", candidates)
    assert compatible == ["1.5.0", "2.0.0", "2.5.0"], f"Filtered versions mismatch: {compatible}"


def test_requirement_parsing_and_marker_evaluation():
    """Assertion 3: packaging.requirements.Requirement parses package dependency requirements with extras and environment markers."""
    req_text = "requests[security,tests]>=2.28.0,<3.0.0; python_version >= '3.8'"
    req = Requirement(req_text)

    assert req.name == "requests"
    assert req.extras == {"security", "tests"}
    assert req.specifier.contains("2.28.1") is True
    assert req.specifier.contains("3.0.0") is False
    assert req.marker is not None

    # Test evaluate_dependency wrapper
    assert evaluate_dependency(req_text, "2.28.1", {"python_version": "3.10"}) is True
    assert evaluate_dependency(req_text, "2.28.1", {"python_version": "3.7"}) is False
    assert evaluate_dependency(req_text, "1.9.0", {"python_version": "3.10"}) is False


def main():
    test_version_parsing_and_ordering()
    test_specifier_matching_and_filtering()
    test_requirement_parsing_and_marker_evaluation()
    print("All contract assertions passed successfully.")


if __name__ == "__main__":
    main()

오리진 시더

익명