From 9cf1e261980b4a8bae0b61e7ee3586ad70be87b3 Mon Sep 17 00:00:00 2001 From: Zo Bot Date: Sat, 27 Jun 2026 03:52:48 +0000 Subject: [PATCH 1/3] decode bytes/bytearray inputs in to_bool os.environb yields bytes on POSIX and the documented use case for to_bool is reading values out of environment variables. The truthy and falsy lookup tuples only contain str and int, so a bytes('true') input raised 'Cannot convert value to bool: b\'true\'' even though its ASCII-decoded value is the canonical truthy literal. Decode bytes and bytearray as ASCII before the lowercase + lookup step, matching the str path. Non-ASCII bytes raise ValueError ('Cannot convert value to bool: ...') the same way an unknown string does, since the decoded text would still not match any known literal. Unknown byte values raise the same ValueError. --- src/attr/converters.py | 15 +++++++++++ tests/test_converters.py | 54 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/src/attr/converters.py b/src/attr/converters.py index 0a79deef0..543aff0ff 100644 --- a/src/attr/converters.py +++ b/src/attr/converters.py @@ -135,6 +135,7 @@ def to_bool(val): - ``"on"`` - ``"1"`` - ``1`` + - bytes/bytearray whose ASCII-decoded value matches any of the strings above Values mapping to `False`: @@ -144,12 +145,26 @@ def to_bool(val): - ``"off"`` - ``"0"`` - ``0`` + - bytes/bytearray whose ASCII-decoded value matches any of the strings above Raises: ValueError: For any other value. + .. versionchanged:: 26.2 + bytes/bytearray inputs are decoded as ASCII before lookup, so values + read from environment variables as bytes (e.g. on Windows or from + ``os.environb``) work without a separate ``.decode("ascii")`` step at + the call site. + .. versionadded:: 21.3.0 """ + if isinstance(val, (bytes, bytearray)): + try: + val = val.decode("ascii") + except UnicodeDecodeError as e: + msg = f"Cannot convert value to bool: {val!r}" + raise ValueError(msg) from e + if isinstance(val, str): val = val.lower() diff --git a/tests/test_converters.py b/tests/test_converters.py index 5726ae210..7fa631df4 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -364,3 +364,57 @@ def test_falsy(self): assert not to_bool("f") assert not to_bool("no") assert not to_bool("off") + + @pytest.mark.parametrize("value", [b"true", b"t", b"yes", b"y", b"on", b"1"]) + def test_truthy_bytes(self, value): + """ + Bytes values that decode to a truthy keyword match the str truthy path. + """ + assert to_bool(value) is True + + @pytest.mark.parametrize( + "value", [b"false", b"f", b"no", b"n", b"off", b"0"] + ) + def test_falsy_bytes(self, value): + """ + Bytes values that decode to a falsy keyword match the str falsy path. + """ + assert to_bool(value) is False + + @pytest.mark.parametrize("value", [b"TRUE", b"Yes", b"OFF", b"1"]) + def test_bytes_are_lowercased(self, value): + """ + Bytes inputs follow the same case-insensitive lookup as str inputs. + """ + assert to_bool(value) is bool(value.decode("ascii").lower() in + {"true", "t", "yes", "y", "on", "1"}) + + def test_bytearray_truthy(self): + """ + bytearray is a bytes subclass and should be decoded the same way. + """ + assert to_bool(bytearray(b"true")) is True + assert to_bool(bytearray(b"off")) is False + + def test_bytes_non_ascii_raises(self): + """ + Bytes that are not valid ASCII raise ValueError with the same shape as + other unconvertible values. + """ + with pytest.raises(ValueError, match="Cannot convert value to bool"): + to_bool(b"\xfftrue") + + def test_bytes_unknown_keyword_raises(self): + """ + Bytes that decode to a value not in either keyword set still raise. + """ + with pytest.raises(ValueError, match="Cannot convert value to bool"): + to_bool(b"maybe") + + def test_bytes_empty_raises(self): + """ + An empty bytes value is not a valid keyword, so it raises the same + error as an empty string would. + """ + with pytest.raises(ValueError, match="Cannot convert value to bool"): + to_bool(b"") From fb2d7d0c68e03898f5a52dddd593a4f50fe916a1 Mon Sep 17 00:00:00 2001 From: Zo Bot Date: Mon, 6 Jul 2026 13:55:26 +0000 Subject: [PATCH 2/3] make_class: accept Attribute instances in 'these' (#1424) When a class is rebuilt from attrs.fields() via attrs.make_class, the 'these' mapping contains Attribute instances rather than _CountingAttr objects. from_counting_attr was only reading the private _default, _validator, and _converter attributes, which Attribute does not expose, so the rebuild crashed with "'Attribute' object has no attribute '_default'". Detect an Attribute argument and read the public default/validator/ converter attributes directly. Add a regression test and a changelog entry. --- changelog.d/1424.change.md | 1 + src/attr/_make.py | 30 ++++++++++++++++++++++++++ tests/test_make.py | 44 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 changelog.d/1424.change.md diff --git a/changelog.d/1424.change.md b/changelog.d/1424.change.md new file mode 100644 index 000000000..2f781292c --- /dev/null +++ b/changelog.d/1424.change.md @@ -0,0 +1 @@ +`attrs.make_class()` now works when its `attrs` argument is a dict of existing `attrs.Attribute` instances (e.g. from `attrs.fields(cls)`), not just fresh `attr.ib()` / `attrs.field()` call \ No newline at end of file diff --git a/src/attr/_make.py b/src/attr/_make.py index 793bfd89d..a7f392af5 100644 --- a/src/attr/_make.py +++ b/src/attr/_make.py @@ -2570,6 +2570,36 @@ def from_counting_attr( elif ca.type is not None: msg = f"Type annotation and type argument cannot both be present for '{name}'." raise ValueError(msg) + + # `from_counting_attr` is also called with already-built `Attribute` + # instances (e.g. when a class is reconstructed from + # `attrs.fields(cls)` via `attrs.make_class`, see #1424). In that case + # `ca` is an `Attribute` and exposes the public `default`/`validator`/ + # `converter` attributes rather than the `_default`/`_validator`/ + # `_converter` internals of `_CountingAttr`. + if isinstance(ca, Attribute): + return cls( + name, + ca.default, + ca.validator, + ca.repr, + None, + ca.hash, + ca.init, + False, + ca.metadata, + type, + ca.converter, + kw_only if ca.kw_only is None else ca.kw_only, + ca.eq, + ca.eq_key, + ca.order, + ca.order_key, + ca.on_setattr, + ca.alias, + ca.alias_is_default, + ) + return cls( name, ca._default, diff --git a/tests/test_make.py b/tests/test_make.py index f83f85234..f932a634d 100644 --- a/tests/test_make.py +++ b/tests/test_make.py @@ -1535,6 +1535,50 @@ def test_make_class_ordered(self): assert "C(a=1, b=2)" == repr(C()) + def test_make_class_from_attrs_fields(self): + """ + make_class can rebuild a class from attrs.fields() output, not only + fresh _CountingAttr / attr.ib() values. + + https://github.com/python-attrs/attrs/issues/1424 + """ + + @attr.s + class Source: + a = attr.ib(type=int) + b = attr.ib( + default="x", validator=attr.validators.instance_of(str) + ) + c = attr.ib( + default=0, + converter=attr.converters.optional(int), + ) + + # Convert the source's _CountingAttr-derived fields into proper + # Attribute instances via make_class, then re-run make_class on those + # Attribute instances. The second pass previously failed with + # "'Attribute' object has no attribute '_default'". + rebuilt = attr.make_class( + "Rebuilt", + {f.name: f for f in attr.fields(Source)}, + ) + + # Order is preserved end-to-end. + assert ["a", "b", "c"] == [a.name for a in attr.fields(rebuilt)] + + # `a` has no default and the rest do, so call with positional a and + # rely on defaults to fill b/c. `7` for c is converted via int. + ri = rebuilt(5) + assert 5 == ri.a + assert "x" == ri.b + assert 0 == ri.c + + ri = rebuilt(5, "hello") + assert "hello" == ri.b + + ri = rebuilt(5, "hello", "7") + assert 7 == ri.c + def test_generic_dynamic_class(self): """ make_class can create generic dynamic classes. From c8b685e314b235bad16fd1f4b53194578c8265ef Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 Jul 2026 13:55:51 +0000 Subject: [PATCH 3/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- changelog.d/1424.change.md | 2 +- tests/test_converters.py | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/changelog.d/1424.change.md b/changelog.d/1424.change.md index 2f781292c..87b5dc2f2 100644 --- a/changelog.d/1424.change.md +++ b/changelog.d/1424.change.md @@ -1 +1 @@ -`attrs.make_class()` now works when its `attrs` argument is a dict of existing `attrs.Attribute` instances (e.g. from `attrs.fields(cls)`), not just fresh `attr.ib()` / `attrs.field()` call \ No newline at end of file +`attrs.make_class()` now works when its `attrs` argument is a dict of existing `attrs.Attribute` instances (e.g. from `attrs.fields(cls)`), not just fresh `attr.ib()` / `attrs.field()` call diff --git a/tests/test_converters.py b/tests/test_converters.py index 7fa631df4..5f2d0b092 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -365,7 +365,9 @@ def test_falsy(self): assert not to_bool("no") assert not to_bool("off") - @pytest.mark.parametrize("value", [b"true", b"t", b"yes", b"y", b"on", b"1"]) + @pytest.mark.parametrize( + "value", [b"true", b"t", b"yes", b"y", b"on", b"1"] + ) def test_truthy_bytes(self, value): """ Bytes values that decode to a truthy keyword match the str truthy path. @@ -386,8 +388,10 @@ def test_bytes_are_lowercased(self, value): """ Bytes inputs follow the same case-insensitive lookup as str inputs. """ - assert to_bool(value) is bool(value.decode("ascii").lower() in - {"true", "t", "yes", "y", "on", "1"}) + assert to_bool(value) is bool( + value.decode("ascii").lower() + in {"true", "t", "yes", "y", "on", "1"} + ) def test_bytearray_truthy(self): """