CodeSampleX

샘플

attrs 26.1.0: Avoid premature validator re-enabling during nested disabled context and handle pre-resolved aliases in field transformers in attrs 26.1.0

검증된 샘플 — pypi attrs 26.1.0: Avoid premature validator re-enabling during nested disabled context and handle pre-resolved aliases in field transformers in…

sha256:89a1110228934559fed8711f85b6f59e237474ccaa0a73797a4d02be4b9d4404

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 python linux x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-16
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

케이스

HOW
목표
Avoid premature validator re-enabling during nested disabled context and handle pre-resolved aliases in field transformers in attrs 26.1.0
패키지
심벌
  • attrs.validators.disabled
  • attrs.validators.get_disabled
  • attrs.define
  • attrs.field
  • attrs.fields
  • attrs.setters.NO_OP
  • attrs.Attribute.alias_is_default
환경
python
생성일
2026-08-16T06:23:31Z

컨트랙트

  1. assert attrs.validators.disabled() context manager is nestable and preserves disabled state across nested context exits
  2. assert validator failures raise ValueError outside disabled context
  3. assert field_transformer receives pre-resolved alias names and alias_is_default booleans on Attribute objects
  4. assert attrs.fields accepts instance objects directly and matches class field definitions
  5. assert frozen classes accept on_setattr=attrs.setters.NO_OP without error

파일

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

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

소스

NOTES.md
# Notes

## Search Results
Calling `search_known_solution` returned existing sample `sha256:db459e2a5619e5bc96877e0fc6aefd6229be3342cc28685624eacd9e170bf4b7` ("Decide whether attrs still buys anything over dataclasses on modern Python, and what changes in each direction"), which evaluated migration trade-offs between `attrs` and standard library `dataclasses`.

## Model Expectation
A model would assume that `with attrs.validators.disabled():` context managers can be safely composed inside nested helper functions without side effects, and that `field_transformer` receives raw `Attribute` objects where default aliases remain `None`.

## Failure Mode on Previous Versions
On `attrs < 26.1.0`, exiting an inner `with attrs.validators.disabled():` block unconditionally calls `set_run_validators(True)` and silently re-enables validation midway through the outer context, while `attrs.fields(instance)` and `@define(frozen=True, on_setattr=NO_OP)` fail loudly at runtime with `TypeError: Passed object must be a class` and `ValueError: Frozen classes can't use on_setattr`.
csx.json
{"case":{"caseId":"case:sha256:ecc637b4385f016e46ba10b35e02fd7f476e00512df91eaca5e0781a19bf6134","contract":["assert attrs.validators.disabled() context manager is nestable and preserves disabled state across nested context exits","assert validator failures raise ValueError outside disabled context","assert field_transformer receives pre-resolved alias names and alias_is_default booleans on Attribute objects","assert attrs.fields accepts instance objects directly and matches class field definitions","assert frozen classes accept on_setattr=attrs.setters.NO_OP without error"],"goal":"Avoid premature validator re-enabling during nested disabled context and handle pre-resolved aliases in field transformers in attrs 26.1.0","kind":"HOW","packages":["pkg:pypi/attrs@26.1.0"],"schemaVersion":1,"symbols":["attrs.validators.disabled","attrs.validators.get_disabled","attrs.define","attrs.field","attrs.fields","attrs.setters.NO_OP","attrs.Attribute.alias_is_default"]},"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/attrs@26.1.0"],"schemaVersion":1,"symbols":["attrs.validators.disabled","attrs.validators.get_disabled","attrs.define","attrs.field","attrs.fields","attrs.setters.NO_OP","attrs.Attribute.alias_is_default"],"verifierAdapter":"python@1"}
requirements.txt
attrs==26.1.0
src/__init__.py
"""Attrs bugfix sample package."""
src/models.py
"""Models demonstrating attrs 26.1.0 behavioral fixes and capabilities."""

from typing import Any, Dict, Tuple
import attrs
from attrs import Attribute, define, field, setters, validators


@define
class PortItem:
    """Class with validated port field."""

    port: int = field(
        validator=[validators.instance_of(int), validators.gt(0)]
    )


TRANSFORMED_FIELD_METADATA: Dict[str, Tuple[str, bool]] = {}


def record_field_metadata(cls: type, fields: Tuple[Attribute, ...]) -> Tuple[Attribute, ...]:
    """Field transformer inspecting resolved aliases and alias_is_default flag."""
    for f in fields:
        TRANSFORMED_FIELD_METADATA[f.name] = (
            f.alias,
            getattr(f, "alias_is_default", None),
        )
    return fields


@define(field_transformer=record_field_metadata)
class AppConfig:
    """Config class demonstrating alias pre-resolution in field_transformer."""

    _secret_key: str = field()
    token_id: int = field(alias="custom_id")
    endpoint: str = field(default="http://localhost:8080")


@define(frozen=True, on_setattr=setters.NO_OP)
class ImmutableSetting:
    """Frozen class accepting on_setattr=NO_OP."""

    key: str
    value: str
test/__init__.py
"""Attrs bugfix test package."""
test/contract.py
import importlib.metadata
import sys
from pathlib import Path

# Add project root to sys.path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import attrs
from attrs import exceptions, fields, validators

from src.models import (
    TRANSFORMED_FIELD_METADATA,
    AppConfig,
    ImmutableSetting,
    PortItem,
)


def test_nested_validator_disabling():
    """Verify that attrs.validators.disabled() context manager is nestable."""
    assert validators.get_disabled() is False

    # Outside disabled context, validation fails as expected
    try:
        PortItem(-1)
        raise AssertionError("Validation should have failed outside disabled context")
    except ValueError as exc:
        assert "must be > 0" in str(exc)

    with validators.disabled():
        # Outer block: validation disabled
        p1 = PortItem(-10)
        assert p1.port == -10
        assert validators.get_disabled() is True

        # Nested inner block
        with validators.disabled():
            p2 = PortItem(-20)
            assert p2.port == -20
            assert validators.get_disabled() is True

        # In attrs 26.1.0+, exiting the inner block preserves the outer disabled state.
        # In <26.1.0, the inner block's finally clause unconditionally re-enabled validators.
        assert validators.get_disabled() is True
        p3 = PortItem(-30)
        assert p3.port == -30

    # Once outermost context exits, validators are fully restored
    assert validators.get_disabled() is False
    try:
        PortItem(-40)
        raise AssertionError("Validation should fail once outermost context exits")
    except ValueError as exc:
        assert "must be > 0" in str(exc)


def test_field_transformer_alias_resolution():
    """Verify that field aliases and alias_is_default are populated before field_transformer runs."""
    # In attrs 26.1.0, field_transformer receives fully resolved Attribute objects.
    # In <26.1.0, Attribute.alias was None for default aliases, and alias_is_default did not exist.
    assert TRANSFORMED_FIELD_METADATA["_secret_key"] == ("secret_key", True)
    assert TRANSFORMED_FIELD_METADATA["token_id"] == ("custom_id", False)
    assert TRANSFORMED_FIELD_METADATA["endpoint"] == ("endpoint", True)

    cfg = AppConfig("vault-token", custom_id=101, endpoint="http://localhost:9000")
    assert cfg._secret_key == "vault-token"
    assert cfg.token_id == 101
    assert cfg.endpoint == "http://localhost:9000"


def test_fields_accepts_instances():
    """Verify that attrs.fields() accepts instances as well as classes."""
    cfg = AppConfig("token", custom_id=1, endpoint="http://localhost:8080")
    # In attrs 26.1.0, fields() accepts instances directly.
    # In <26.1.0, passing an instance raised TypeError: Passed object must be a class.
    inst_fields = fields(cfg)
    cls_fields = fields(AppConfig)
    assert inst_fields == cls_fields
    assert [f.name for f in inst_fields] == ["_secret_key", "token_id", "endpoint"]


def test_frozen_with_noop_on_setattr():
    """Verify that frozen classes allow on_setattr=attrs.setters.NO_OP."""
    # In attrs 26.1.0, setters.NO_OP is accepted alongside None on frozen classes.
    # In <26.1.0, passing on_setattr to a frozen class raised ValueError.
    setting = ImmutableSetting("env", "production")
    assert setting.key == "env"
    assert setting.value == "production"

    try:
        setting.key = "staging"
        raise AssertionError("Frozen instance must reject attribute modification")
    except exceptions.FrozenInstanceError:
        pass


if __name__ == "__main__":
    test_nested_validator_disabling()
    test_field_transformer_alias_resolution()
    test_fields_accepts_instances()
    test_frozen_with_noop_on_setattr()
    print("contract ok:", importlib.metadata.version("attrs"))

오리진 시더

csx-seed