CodeSampleX

샘플

packaging 26.3: Parse PEP 508 environment markers and evaluate them against environment dictionaries with boolean logic and extra normalization using packaging.markers

검증된 샘플 — pypi packaging 26.3: Parse PEP 508 environment markers and evaluate them against environment dictionaries with boolean logic and extra normalization…

sha256:856cc9b895735f9b6352d7707412b0ed349fb5d6c6aabcdfc9af0f8fd4bbc4f0

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Parse PEP 508 environment markers and evaluate them against environment dictionaries with boolean logic and extra normalization using packaging.markers
패키지
심벌
  • packaging.markers.InvalidMarker
  • packaging.markers.Marker
  • packaging.markers.default_environment
생성일
2026-08-27T18:32:25Z

컨트랙트

  1. parse PEP 508 environment markers with boolean operators and version comparisons
  2. evaluate markers against custom environment dictionaries overriding os and python version
  3. evaluate markers against the runtime default environment
  4. match extras with automatic canonicalization of hyphens and underscores
  5. raise InvalidMarker on malformed expressions or invalid marker variable names

파일

  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/__init__.py
  • src/marker_evaluator.py
  • 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: Parse PEP 508 environment markers and evaluate them against environment dictionaries with boolean logic and extra normalization using packaging.markers
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/packaging@26.3
Demonstrate these symbols/APIs:
  - packaging.markers.InvalidMarker
  - packaging.markers.Marker
  - packaging.markers.default_environment

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:c08ec3fdac3b6fa92550b9dde39a580ade33c4c69894cbfc983cb1c8a3d2b467","contract":["parse PEP 508 environment markers with boolean operators and version comparisons","evaluate markers against custom environment dictionaries overriding os and python version","evaluate markers against the runtime default environment","match extras with automatic canonicalization of hyphens and underscores","raise InvalidMarker on malformed expressions or invalid marker variable names"],"goal":"Parse PEP 508 environment markers and evaluate them against environment dictionaries with boolean logic and extra normalization using packaging.markers","kind":"HOW","packages":["pkg:pypi/packaging@26.3"],"schemaVersion":1,"symbols":["packaging.markers.InvalidMarker","packaging.markers.Marker","packaging.markers.default_environment"]},"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/packaging@26.3"],"schemaVersion":1,"subject":"pkg:pypi/packaging@26.3","symbols":["packaging.markers.InvalidMarker","packaging.markers.Marker","packaging.markers.default_environment"],"verifierAdapter":"python@1"}
requirements.txt
packaging==26.3
spec.json
{
  "schemaVersion": 1,
  "goal": "Parse PEP 508 environment markers and evaluate them against environment dictionaries with boolean logic and extra normalization using packaging.markers",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/packaging@26.3"
  ],
  "symbols": [
    "packaging.markers.InvalidMarker",
    "packaging.markers.Marker",
    "packaging.markers.default_environment"
  ]
}
src/__init__.py
"""PEP 508 environment marker parsing and evaluation utilities."""
src/marker_evaluator.py
"""PEP 508 environment marker parsing and evaluation using packaging.markers."""

from collections.abc import Mapping
from packaging.markers import InvalidMarker, Marker, default_environment


def parse_marker(marker_expr: str) -> Marker:
    """Parse a PEP 508 marker expression.

    Raises InvalidMarker if syntax is invalid or references unknown marker variables.
    """
    return Marker(marker_expr)


def is_marker_valid(marker_expr: str) -> bool:
    """Check if a marker expression is syntactically valid according to PEP 508."""
    try:
        Marker(marker_expr)
        return True
    except InvalidMarker:
        return False


def evaluate_marker(
    marker_expr: str,
    environment: Mapping[str, str] | None = None,
) -> bool:
    """Evaluate a marker expression against an environment mapping.

    If environment is None, the runtime default environment is used.
    """
    marker = Marker(marker_expr)
    return marker.evaluate(environment)


def evaluate_with_extra(marker_expr: str, extra: str) -> bool:
    """Evaluate a marker with an active extra, canonicalizing name per PEP 685."""
    marker = Marker(marker_expr)
    return marker.evaluate({"extra": extra})


def get_system_marker_environment() -> dict[str, str]:
    """Return the default environment dictionary detected from the running process."""
    return default_environment()
test/contract.py
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from packaging.markers import InvalidMarker
from src.marker_evaluator import (
    evaluate_marker,
    evaluate_with_extra,
    get_system_marker_environment,
    is_marker_valid,
    parse_marker,
)

# 1. Parse and evaluate compound marker with boolean operators and version comparisons
marker = parse_marker("python_version >= '3.8' and (os_name == 'posix' or sys_platform == 'linux')")
assert str(marker) == 'python_version >= "3.8" and (os_name == "posix" or sys_platform == "linux")'

# 2. Evaluate against custom environment dictionaries overriding os and python version
posix_env = {"python_version": "3.11", "os_name": "posix", "sys_platform": "darwin"}
assert evaluate_marker("python_version >= '3.8' and os_name == 'posix'", posix_env) is True

win_env = {"python_version": "3.11", "os_name": "nt", "sys_platform": "win32"}
assert evaluate_marker("python_version >= '3.8' and os_name == 'posix'", win_env) is False

old_py_env = {"python_version": "3.7", "os_name": "posix", "sys_platform": "darwin"}
assert evaluate_marker("python_version >= '3.8' and os_name == 'posix'", old_py_env) is False

# 'in' and 'not in' operators
assert evaluate_marker("sys_platform in 'linux, darwin'", posix_env) is True
assert evaluate_marker("sys_platform in 'linux, darwin'", win_env) is False

# 3. Evaluate markers against runtime default environment
system_env = get_system_marker_environment()
assert "python_version" in system_env
assert "sys_platform" in system_env
assert "os_name" in system_env
assert evaluate_marker(f"os_name == '{system_env['os_name']}'") is True

# 4. Match extras with automatic canonicalization of hyphens and underscores (PEP 685)
assert evaluate_with_extra("extra == 'secure-socks'", "secure_socks") is True
assert evaluate_with_extra("extra == 'secure_socks'", "secure-socks") is True
assert evaluate_with_extra("extra == 'secure-socks'", "other") is False

# 5. InvalidMarker error handling for syntax errors and unknown marker variable names
assert is_marker_valid("python_version >= '3.8'") is True
assert is_marker_valid("python_version >> '3.8'") is False
assert is_marker_valid("unknown_var == 'value'") is False
assert is_marker_valid("") is False

try:
    parse_marker("unknown_marker_var == '1.0'")
    assert False, "Should have raised InvalidMarker"
except InvalidMarker:
    pass

print("CONTRACT PASS: packaging markers parsed, validated, and evaluated correctly")

오리진 시더

익명