enumplus 1.2.2__tar.gz → 1.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. {enumplus-1.2.2 → enumplus-1.2.3}/AGENTS.md +20 -3
  2. {enumplus-1.2.2 → enumplus-1.2.3}/CHANGELOG.md +38 -2
  3. {enumplus-1.2.2 → enumplus-1.2.3}/PKG-INFO +4 -7
  4. {enumplus-1.2.2 → enumplus-1.2.3}/README.md +3 -6
  5. {enumplus-1.2.2 → enumplus-1.2.3}/enumplus/enum.py +136 -34
  6. {enumplus-1.2.2 → enumplus-1.2.3}/enumplus/pydantic.py +2 -0
  7. {enumplus-1.2.2 → enumplus-1.2.3}/enumplus/serialize.py +5 -1
  8. {enumplus-1.2.2 → enumplus-1.2.3}/pyproject.toml +2 -1
  9. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_compatibility.py +1 -1
  10. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_edge_cases.py +280 -0
  11. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_enum.py +1 -1
  12. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_metadata_unpacking.py +39 -0
  13. {enumplus-1.2.2 → enumplus-1.2.3}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  14. {enumplus-1.2.2 → enumplus-1.2.3}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  15. {enumplus-1.2.2 → enumplus-1.2.3}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  16. {enumplus-1.2.2 → enumplus-1.2.3}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  17. {enumplus-1.2.2 → enumplus-1.2.3}/.github/workflows/ci.yml +0 -0
  18. {enumplus-1.2.2 → enumplus-1.2.3}/.github/workflows/release.yml +0 -0
  19. {enumplus-1.2.2 → enumplus-1.2.3}/.gitignore +0 -0
  20. {enumplus-1.2.2 → enumplus-1.2.3}/CODE_OF_CONDUCT.md +0 -0
  21. {enumplus-1.2.2 → enumplus-1.2.3}/CONTRIBUTING.md +0 -0
  22. {enumplus-1.2.2 → enumplus-1.2.3}/LICENSE +0 -0
  23. {enumplus-1.2.2 → enumplus-1.2.3}/SECURITY.md +0 -0
  24. {enumplus-1.2.2 → enumplus-1.2.3}/SUPPORT.md +0 -0
  25. {enumplus-1.2.2 → enumplus-1.2.3}/enumplus/__init__.py +0 -0
  26. {enumplus-1.2.2 → enumplus-1.2.3}/enumplus/py.typed +0 -0
  27. {enumplus-1.2.2 → enumplus-1.2.3}/tests/__init__.py +0 -0
  28. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_new_features.py +0 -0
  29. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_ordered.py +0 -0
  30. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_public_api.py +0 -0
  31. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_pydantic.py +0 -0
  32. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_serialize.py +0 -0
  33. {enumplus-1.2.2 → enumplus-1.2.3}/tests/test_type_hints.py +0 -0
@@ -24,11 +24,28 @@ Requires Python `>=3.11`.
24
24
  - Support `auto()` following a metadata tuple on Python 3.11–3.14.
25
25
  - `serialize_by_name` is a reserved class config key: it must be a `bool`
26
26
  (`TypeError` otherwise) and can never be a member name.
27
+ - Metadata tuples are detected with `type(value) is tuple` (not
28
+ `isinstance`), so tuple subclasses such as `NamedTuple` stay intact as
29
+ member values.
30
+ - During class creation, `EnumMeta.__new__` injects the collected metadata map
31
+ as the temporary `_enumplus_pending_metadata` class attribute and removes it
32
+ after member post-processing. `Enum._resolve_metadata()` reads `_metadata_`
33
+ first, then the pending map, so `label`/`metadata`/metadata attributes work
34
+ inside member `__init__`. Members created via `enum._simple_enum` never get
35
+ `_metadata_`/`_label_`/`_index_`; accessors degrade gracefully to auto
36
+ labels, empty metadata, and `_sort_order_`-based ordering.
27
37
  - Auto-generated labels use `name.replace("_", " ").title()`. `filter(label=...)`
28
38
  matches the evaluated label, not the raw metadata dict.
29
- - `Enum.__eq__` and `EnumMeta.__contains__` use `_safe_equal`, which coerces
30
- `a == b` to a `bool` without raising on shape/length mismatches (e.g. NumPy
31
- arrays, unhashable container values).
39
+ - `Enum.__eq__` compares enum-to-enum by identity links only (`self is other`,
40
+ `self.value is other`, `other.value is self`) and everything else through
41
+ `_safe_equal`, which coerces `a == b` to a `bool` without raising on
42
+ shape/length mismatches (e.g. NumPy arrays, unhashable container values).
43
+ `EnumMeta.__contains__`, `from_value()`, `is_valid()`, and `_missing_()`
44
+ share `_match_enum_member` for the enum-member branch.
45
+ - `Enum._missing_` is implemented so `cls(value)` lookup agrees with
46
+ `from_value()` on misses. For classes mixing in `enum.Flag`/`enum.IntFlag`
47
+ it delegates to the nearest Flag-family `_missing_` in the MRO, preserving
48
+ composite pseudo-members and `boundary=` semantics.
32
49
  - `Enum.__hash__` uses `hash(self.value)` when possible and falls back to
33
50
  `id(self)` for unhashable values, so enum members with list/dict values are
34
51
  still usable as dict keys.
@@ -5,7 +5,42 @@ All notable changes to this project are documented in this file.
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [Unreleased]
8
+ ## [1.2.3] - 2026-11-18
9
+
10
+ ### Fixed
11
+
12
+ - `label`, `metadata`, and metadata attributes are now readable inside a
13
+ member's `__init__`. stdlib runs `__init__` during class creation, before
14
+ `EnumMeta.__new__` could attach `_metadata_`; metadata is now resolved
15
+ through a pending map while the class is being built.
16
+ - Members created via `enum._simple_enum` no longer raise `AttributeError` on
17
+ `label`, `metadata`, metadata attributes, `filter()`, `to_dict()`,
18
+ `to_json()`, or `OrderedEnum` comparisons. They fall back to auto-generated
19
+ labels, empty metadata, and the stdlib `_sort_order_` for ordering.
20
+ - Member values that are tuple subclasses (e.g. `NamedTuple` instances) are no
21
+ longer mistaken for `(value, metadata)` tuples and unwrapped. Only plain
22
+ `tuple` values are treated as metadata declarations.
23
+ - `member == other` now returns `True` when `other` is this member's value
24
+ object or wraps it as its value, symmetrically in both directions. Equality
25
+ and hashing stay consistent: `Outer.A == Inner.X` now agrees with
26
+ `Outer.A == "x"` when `Outer.A.value is Inner.X`.
27
+ - `cls(value)` lookup now delegates misses to a `_missing_` hook that uses the
28
+ same safe equality as `from_value()`, so call-style lookup and
29
+ `from_value()` agree. Classes mixing in `enum.Flag`/`enum.IntFlag` keep the
30
+ stdlib lookup, so composite values (`F.A | F.B`) and `boundary=` handling
31
+ still work.
32
+ - `in`, `from_value()`, and `is_valid()` now also match a foreign enum member
33
+ whose own value is a member of the queried enum (e.g. `Outer.A in Inner`
34
+ when `Outer.A.value is Inner.X`), consistent with member equality.
35
+ - `map()` raises `TypeError` for non-mapping arguments instead of
36
+ `AttributeError`.
37
+
38
+ ### Changed
39
+
40
+ - Removed `@dataclass_transform()` from the metaclass. It made type checkers
41
+ require `_metadata_`/`_index_` constructor arguments on calls like
42
+ `Color("red")`. Metadata attribute access still resolves through
43
+ `__getattr__` and is typed as `Any`.
9
44
 
10
45
  ## [1.2.2] - 2026-10-06
11
46
 
@@ -110,7 +145,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
110
145
  - Pydantic v2 integration via `__get_pydantic_core_schema__`.
111
146
  - Full test suite, CI, and release workflows.
112
147
 
113
- [Unreleased]: https://github.com/MathiasPaulenko/enumplus/compare/v1.2.2...HEAD
148
+ [Unreleased]: https://github.com/MathiasPaulenko/enumplus/compare/v1.2.3...HEAD
149
+ [1.2.3]: https://github.com/MathiasPaulenko/enumplus/releases/tag/v1.2.3
114
150
  [1.2.2]: https://github.com/MathiasPaulenko/enumplus/releases/tag/v1.2.2
115
151
  [1.2.1]: https://github.com/MathiasPaulenko/enumplus/releases/tag/v1.2.1
116
152
  [1.2.0]: https://github.com/MathiasPaulenko/enumplus/releases/tag/v1.2.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: enumplus
3
- Version: 1.2.2
3
+ Version: 1.2.3
4
4
  Summary: Enhanced Python enums with metadata, serialization, and choices
5
5
  Project-URL: Homepage, https://pypi.org/project/enumplus/
6
6
  Project-URL: Repository, https://github.com/MathiasPaulenko/enumplus
@@ -438,20 +438,17 @@ Callable labels work everywhere: `choices()`, `to_dict()`, `to_json()`, `labels(
438
438
 
439
439
  ### Type hints in metadata
440
440
 
441
- The `@dataclass_transform()` decorator on the metaclass enables type checkers to recognize metadata fields.
441
+ Metadata attributes are resolved at runtime through `__getattr__`, which
442
+ returns `Any`. Type checkers therefore accept `member.<key>` accesses as
443
+ `Any`, but cannot verify individual key names or value types.
442
444
 
443
445
  ```python
444
446
  class Color(Enum):
445
447
  RED = ("red", {"hex": "#FF0000"})
446
448
 
447
- # Type checkers recognize .hex as a valid attribute
448
449
  Color.RED.hex # inferred as Any via __getattr__
449
450
  ```
450
451
 
451
- > **Note:** Type inference for metadata attributes depends on the type checker.
452
- > The `@dataclass_transform()` decorator provides the structural hint, but
453
- > runtime attribute access goes through `__getattr__`, which returns `Any`.
454
-
455
452
  ## Migration from stdlib
456
453
 
457
454
  Just change one import:
@@ -405,20 +405,17 @@ Callable labels work everywhere: `choices()`, `to_dict()`, `to_json()`, `labels(
405
405
 
406
406
  ### Type hints in metadata
407
407
 
408
- The `@dataclass_transform()` decorator on the metaclass enables type checkers to recognize metadata fields.
408
+ Metadata attributes are resolved at runtime through `__getattr__`, which
409
+ returns `Any`. Type checkers therefore accept `member.<key>` accesses as
410
+ `Any`, but cannot verify individual key names or value types.
409
411
 
410
412
  ```python
411
413
  class Color(Enum):
412
414
  RED = ("red", {"hex": "#FF0000"})
413
415
 
414
- # Type checkers recognize .hex as a valid attribute
415
416
  Color.RED.hex # inferred as Any via __getattr__
416
417
  ```
417
418
 
418
- > **Note:** Type inference for metadata attributes depends on the type checker.
419
- > The `@dataclass_transform()` decorator provides the structural hint, but
420
- > runtime attribute access goes through `__getattr__`, which returns `Any`.
421
-
422
419
  ## Migration from stdlib
423
420
 
424
421
  Just change one import:
@@ -2,8 +2,9 @@ from __future__ import annotations
2
2
 
3
3
  import enum
4
4
  import sys
5
+ from collections.abc import Mapping
5
6
  from types import NotImplementedType
6
- from typing import Any, Self, TypeVar, dataclass_transform, overload
7
+ from typing import Any, Self, TypeVar, overload
7
8
 
8
9
  if sys.version_info >= (3, 13):
9
10
  from enum import EnumDict
@@ -12,6 +13,7 @@ else:
12
13
 
13
14
  _SENTINEL = object()
14
15
  _T = TypeVar("_T")
16
+ _PENDING_METADATA_ATTR = "_enumplus_pending_metadata"
15
17
 
16
18
 
17
19
  class _EnumPlusDict(EnumDict):
@@ -52,7 +54,7 @@ class _EnumPlusDict(EnumDict):
52
54
  return
53
55
 
54
56
  if (
55
- isinstance(value, tuple)
57
+ type(value) is tuple
56
58
  and len(value) == 2
57
59
  and isinstance(value[1], dict)
58
60
  ):
@@ -82,7 +84,21 @@ def _safe_equal(a: Any, b: Any) -> bool:
82
84
  return False
83
85
 
84
86
 
85
- @dataclass_transform()
87
+ def _match_enum_member(cls: Any, item: enum.Enum) -> Any | None:
88
+ """Return the member linked to ``item`` by value-object identity.
89
+
90
+ An enum member input matches when it IS a member's value object
91
+ (``member.value is item``) or when its own value object IS a member
92
+ (``member is item.value``). Identity matching avoids the cross-enum
93
+ false positives that plain equality would produce.
94
+ """
95
+ item_value = item.__dict__.get("_value_", _SENTINEL)
96
+ for member in cls:
97
+ if member.value is item or member is item_value:
98
+ return member
99
+ return None
100
+
101
+
86
102
  class EnumMeta(enum.EnumMeta):
87
103
  """Metaclass for enumplus enums.
88
104
 
@@ -131,7 +147,7 @@ class EnumMeta(enum.EnumMeta):
131
147
  class_config = {}
132
148
  for key, value in list(namespace.items()):
133
149
  if (
134
- isinstance(value, tuple)
150
+ type(value) is tuple
135
151
  and len(value) == 2
136
152
  and isinstance(value[1], dict)
137
153
  ):
@@ -139,6 +155,13 @@ class EnumMeta(enum.EnumMeta):
139
155
  member_metadata[key] = metadata
140
156
  dict.__setitem__(namespace, key, actual_value)
141
157
 
158
+ # Expose the pending metadata map as a temporary class attribute so
159
+ # members can resolve it during __init__ — stdlib runs member
160
+ # __init__ inside super().__new__, before _metadata_ exists.
161
+ had_pending = _PENDING_METADATA_ATTR in namespace
162
+ previous_pending = dict.get(namespace, _PENDING_METADATA_ATTR)
163
+ dict.__setitem__(namespace, _PENDING_METADATA_ATTR, member_metadata)
164
+
142
165
  new_cls = super().__new__(cls, name, bases, namespace, **kwargs)
143
166
 
144
167
  for key, value in class_config.items():
@@ -161,6 +184,11 @@ class EnumMeta(enum.EnumMeta):
161
184
 
162
185
  member._index_ = index
163
186
 
187
+ if had_pending:
188
+ setattr(new_cls, _PENDING_METADATA_ATTR, previous_pending)
189
+ else:
190
+ delattr(new_cls, _PENDING_METADATA_ATTR)
191
+
164
192
  return new_cls
165
193
 
166
194
  def __contains__(cls, item: Any) -> bool:
@@ -168,12 +196,7 @@ class EnumMeta(enum.EnumMeta):
168
196
  return True
169
197
  member: Any
170
198
  if isinstance(item, enum.Enum):
171
- # Foreign enum member: only match if a member's value IS this
172
- # exact enum member (identity), not just equal by value.
173
- for member in cls:
174
- if member.value is item:
175
- return True
176
- return False
199
+ return _match_enum_member(cls, item) is not None
177
200
  for member in cls:
178
201
  if _safe_equal(member.value, item):
179
202
  return True
@@ -203,6 +226,25 @@ class Enum(enum.Enum, metaclass=EnumMeta):
203
226
  _metadata_: dict[str, Any]
204
227
  _index_: int
205
228
 
229
+ def _resolve_metadata(self) -> dict[str, Any]:
230
+ """Return this member's metadata, even while ``__init__`` is running.
231
+
232
+ stdlib runs member ``__init__`` before ``EnumMeta.__new__`` can attach
233
+ ``_metadata_``; during that window the map is reachable through the
234
+ temporary ``_enumplus_pending_metadata`` class attribute. Members
235
+ created via ``enum._simple_enum`` never get ``_metadata_`` at all and
236
+ resolve to an empty dict.
237
+ """
238
+ metadata: dict[str, Any] | None = self.__dict__.get("_metadata_")
239
+ if metadata is not None:
240
+ return metadata
241
+ pending = type(self).__dict__.get(_PENDING_METADATA_ATTR)
242
+ name: str | None = self.__dict__.get("_name_")
243
+ if not isinstance(pending, dict) or name is None:
244
+ return {}
245
+ found = pending.get(name, {})
246
+ return found if isinstance(found, dict) else {}
247
+
206
248
  @property
207
249
  def label(self) -> str:
208
250
  """Human-readable label for this member.
@@ -210,7 +252,12 @@ class Enum(enum.Enum, metaclass=EnumMeta):
210
252
  If the label was set to a callable, it is evaluated on every access.
211
253
  Falls back to ``name.replace("_", " ").title()`` when no label is set.
212
254
  """
213
- label = self._label_
255
+ label = self.__dict__.get("_label_", _SENTINEL)
256
+ if label is _SENTINEL:
257
+ raw = self._resolve_metadata().get("label")
258
+ if raw is None:
259
+ raw = (self.__dict__.get("_name_") or "").replace("_", " ").title()
260
+ label = raw
214
261
  if callable(label):
215
262
  return str(label())
216
263
  return str(label)
@@ -218,16 +265,17 @@ class Enum(enum.Enum, metaclass=EnumMeta):
218
265
  @property
219
266
  def metadata(self) -> dict[str, Any]:
220
267
  """Metadata dictionary attached to this member."""
221
- return self._metadata_
268
+ return self._resolve_metadata()
222
269
 
223
270
  def __getattr__(self, name: str) -> Any:
224
271
  if name.startswith("_"):
225
272
  raise AttributeError(name)
226
273
  try:
227
- return self._metadata_[name]
274
+ return self._resolve_metadata()[name]
228
275
  except KeyError:
276
+ member_name = self.__dict__.get("_name_", "?")
229
277
  raise AttributeError(
230
- f"{type(self).__name__}.{self.name!s} has no attribute {name!r}"
278
+ f"{type(self).__name__}.{member_name!s} has no attribute {name!r}"
231
279
  ) from None
232
280
 
233
281
  def __str__(self) -> str:
@@ -238,7 +286,14 @@ class Enum(enum.Enum, metaclass=EnumMeta):
238
286
 
239
287
  def __eq__(self, other: object) -> bool:
240
288
  if isinstance(other, enum.Enum):
241
- return self is other
289
+ # Identity only: a member equals another member when it is the same
290
+ # object, when it IS this member's value object, or when the other
291
+ # member's value object IS this member.
292
+ return (
293
+ self is other
294
+ or self.__dict__.get("_value_") is other
295
+ or other.__dict__.get("_value_") is self
296
+ )
242
297
  return _safe_equal(self.value, other)
243
298
 
244
299
  def __hash__(self) -> int:
@@ -247,6 +302,34 @@ class Enum(enum.Enum, metaclass=EnumMeta):
247
302
  except TypeError:
248
303
  return id(self)
249
304
 
305
+ @classmethod
306
+ def _missing_(cls, value: Any) -> Any:
307
+ """Lookup fallback for ``cls(value)``, matching ``from_value()`` semantics.
308
+
309
+ Keeps ``cls(value)`` consistent with ``cls.from_value(value)``: enum
310
+ member inputs match by value-object identity, everything else by safe
311
+ equality. Without it, ``cls(value)`` raises for values that
312
+ ``from_value()`` resolves (e.g. a member whose value is itself an enum
313
+ member compared through a non-hash-stable ``__eq__``).
314
+
315
+ Classes mixing in ``enum.Flag`` delegate to the stdlib implementation:
316
+ flag lookups need boundary handling and composite pseudo-members.
317
+ """
318
+ if issubclass(cls, enum.Flag):
319
+ for base in cls.__mro__:
320
+ if not issubclass(base, enum.Flag):
321
+ continue
322
+ missing = base.__dict__.get("_missing_")
323
+ if missing is not None:
324
+ return missing.__get__(None, cls)(value)
325
+ return None
326
+ if isinstance(value, enum.Enum):
327
+ return _match_enum_member(cls, value)
328
+ for member in cls:
329
+ if _safe_equal(member.value, value):
330
+ return member
331
+ return None
332
+
250
333
  @classmethod
251
334
  def choices(cls) -> list[tuple[Any, str]]:
252
335
  """Return ``[(value, label), ...]`` for forms and dropdowns."""
@@ -289,11 +372,9 @@ class Enum(enum.Enum, metaclass=EnumMeta):
289
372
  if isinstance(value, cls):
290
373
  return value
291
374
  if isinstance(value, enum.Enum):
292
- # Foreign enum member: only match if a member's value IS this
293
- # exact enum member (identity), not just equal by value.
294
- for member in cls:
295
- if member.value is value:
296
- return member
375
+ member = _match_enum_member(cls, value)
376
+ if member is not None:
377
+ return member
297
378
  if default is not _SENTINEL:
298
379
  return default
299
380
  raise ValueError(f"{value!r} is not a valid {cls.__name__} value")
@@ -365,12 +446,7 @@ class Enum(enum.Enum, metaclass=EnumMeta):
365
446
  if isinstance(value, cls):
366
447
  return True
367
448
  if isinstance(value, enum.Enum):
368
- # Foreign enum member: only match if a member's value IS this
369
- # exact enum member (identity), not just equal by value.
370
- for member in cls:
371
- if member.value is value:
372
- return True
373
- return False
449
+ return _match_enum_member(cls, value) is not None
374
450
  for member in cls:
375
451
  if member is value or _safe_equal(member.value, value):
376
452
  return True
@@ -443,12 +519,19 @@ class Enum(enum.Enum, metaclass=EnumMeta):
443
519
  return members[-1]
444
520
 
445
521
  @classmethod
446
- def map(cls, mapping: dict[Self, Any]) -> dict[str, Any]:
522
+ def map(cls, mapping: Mapping[Self, Any]) -> dict[str, Any]:
447
523
  """Map each member to a value via ``mapping``.
448
524
 
449
525
  Returns ``{name: mapped_value}`` for every member. Members not present
450
526
  in ``mapping`` get ``None``.
527
+
528
+ Raises:
529
+ TypeError: If ``mapping`` is not a mapping.
451
530
  """
531
+ if not isinstance(mapping, Mapping):
532
+ raise TypeError(
533
+ f"map expects a mapping, got {type(mapping).__name__}"
534
+ )
452
535
  result: dict[str, Any] = {}
453
536
  for member in cls:
454
537
  result[member.name] = mapping.get(member, None)
@@ -461,7 +544,7 @@ class Enum(enum.Enum, metaclass=EnumMeta):
461
544
  for member in cls:
462
545
  label = member.label
463
546
  metadata: dict[str, Any] = {}
464
- for k, v in member._metadata_.items():
547
+ for k, v in member.metadata.items():
465
548
  if k == "label" and callable(v):
466
549
  metadata[k] = label
467
550
  else:
@@ -484,11 +567,11 @@ class Enum(enum.Enum, metaclass=EnumMeta):
484
567
  return list(cls)
485
568
  result: list[Self] = []
486
569
  for member in cls:
570
+ metadata = member.metadata
487
571
  if all(
488
572
  _safe_equal(member.label, value)
489
573
  if key == "label"
490
- else key in member._metadata_
491
- and _safe_equal(member._metadata_[key], value)
574
+ else key in metadata and _safe_equal(metadata[key], value)
492
575
  for key, value in kwargs.items()
493
576
  ):
494
577
  result.append(member)
@@ -529,22 +612,41 @@ class OrderedEnum(Enum):
529
612
  Also works with ``sorted()``, ``min()``, and ``max()``.
530
613
  """
531
614
 
615
+ def _sort_index(self) -> int:
616
+ """Declaration-order index used by the comparison operators.
617
+
618
+ ``_index_`` is attached by ``EnumMeta.__new__`` after member creation.
619
+ Members built outside that path (``enum._simple_enum``) fall back to
620
+ the stdlib ``_sort_order_``, and during member ``__init__`` — before
621
+ either exists — to the number of members registered so far.
622
+ """
623
+ index: int | None = self.__dict__.get("_index_")
624
+ if index is not None:
625
+ return index
626
+ sort_order: int | None = self.__dict__.get("_sort_order_")
627
+ if sort_order is not None:
628
+ return sort_order
629
+ names: list[str] | None = type(self).__dict__.get("_member_names_")
630
+ if names is not None:
631
+ return len(names)
632
+ return 0
633
+
532
634
  def __lt__(self, other: object) -> bool | NotImplementedType:
533
635
  if not isinstance(other, type(self)):
534
636
  return NotImplemented
535
- return self._index_ < other._index_
637
+ return self._sort_index() < other._sort_index()
536
638
 
537
639
  def __le__(self, other: object) -> bool | NotImplementedType:
538
640
  if not isinstance(other, type(self)):
539
641
  return NotImplemented
540
- return self._index_ <= other._index_
642
+ return self._sort_index() <= other._sort_index()
541
643
 
542
644
  def __gt__(self, other: object) -> bool | NotImplementedType:
543
645
  if not isinstance(other, type(self)):
544
646
  return NotImplemented
545
- return self._index_ > other._index_
647
+ return self._sort_index() > other._sort_index()
546
648
 
547
649
  def __ge__(self, other: object) -> bool | NotImplementedType:
548
650
  if not isinstance(other, type(self)):
549
651
  return NotImplemented
550
- return self._index_ >= other._index_
652
+ return self._sort_index() >= other._sort_index()
@@ -31,6 +31,8 @@ def get_pydantic_core_schema(
31
31
  from pydantic_core import core_schema
32
32
 
33
33
  serialize_by_name = getattr(cls, "serialize_by_name", False)
34
+ if not isinstance(serialize_by_name, bool):
35
+ serialize_by_name = False
34
36
 
35
37
  def validate(value: Any) -> Any:
36
38
  if isinstance(value, cls):
@@ -21,11 +21,15 @@ def to_json(cls: type[Enum]) -> str:
21
21
  ]
22
22
  }
23
23
  """
24
+ if not isinstance(cls, type) or not issubclass(cls, Enum):
25
+ raise TypeError(
26
+ f"to_json expects an Enum subclass, got {type(cls).__name__}"
27
+ )
24
28
  members: list[dict[str, Any]] = []
25
29
  for member in cls:
26
30
  label = member.label
27
31
  metadata: dict[str, Any] = {}
28
- for k, v in member._metadata_.items():
32
+ for k, v in member.metadata.items():
29
33
  if k == "label" and callable(v):
30
34
  metadata[k] = label
31
35
  else:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "enumplus"
7
- version = "1.2.2"
7
+ version = "1.2.3"
8
8
  description = "Enhanced Python enums with metadata, serialization, and choices"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -53,3 +53,4 @@ strict = true
53
53
 
54
54
  [tool.pytest.ini_options]
55
55
  testpaths = ["tests"]
56
+ asyncio_default_fixture_loop_scope = "function"
@@ -33,7 +33,7 @@ def test_access_by_value() -> None:
33
33
  RED = "red"
34
34
  GREEN = "green"
35
35
 
36
- assert Color("red") is Color.RED # type: ignore[call-arg]
36
+ assert Color("red") is Color.RED
37
37
 
38
38
 
39
39
  def test_iteration_order() -> None:
@@ -1492,3 +1492,283 @@ def test_filter_by_explicit_label() -> None:
1492
1492
  assert C.filter(label="Alpha") == [C.A]
1493
1493
  assert C.filter(label="Alpha", kind="k") == [C.A]
1494
1494
  assert C.filter(label="Alpha", kind="other") == []
1495
+
1496
+
1497
+ # ---------- Metadata access during member __init__ ----------
1498
+
1499
+
1500
+ def test_member_init_reads_label() -> None:
1501
+ seen: list[str] = []
1502
+
1503
+ class Color(Enum):
1504
+ RED = ("red", {"label": "Custom Red"})
1505
+ GREEN = "green"
1506
+
1507
+ def __init__(self, *_args: object) -> None:
1508
+ seen.append(self.label)
1509
+
1510
+ assert seen == ["Custom Red", "Green"]
1511
+
1512
+
1513
+ def test_member_init_reads_metadata() -> None:
1514
+ seen: list[dict[str, Any]] = []
1515
+
1516
+ class Color(Enum):
1517
+ RED = ("red", {"hex": "#FF0000"})
1518
+ BLUE = "blue"
1519
+
1520
+ def __init__(self, *_args: object) -> None:
1521
+ seen.append(dict(self.metadata))
1522
+
1523
+ assert seen == [{"hex": "#FF0000"}, {}]
1524
+
1525
+
1526
+ def test_member_init_reads_metadata_attribute() -> None:
1527
+ seen: list[Any] = []
1528
+
1529
+ class Color(Enum):
1530
+ RED = ("red", {"hex": "#FF0000"})
1531
+
1532
+ def __init__(self, *_args: object) -> None:
1533
+ seen.append(self.hex)
1534
+
1535
+ assert seen == ["#FF0000"]
1536
+
1537
+
1538
+ def test_member_init_str_uses_label() -> None:
1539
+ seen: list[str] = []
1540
+
1541
+ class Status(Enum):
1542
+ IN_PROGRESS = "in_progress"
1543
+
1544
+ def __init__(self, *_args: object) -> None:
1545
+ seen.append(str(self))
1546
+
1547
+ assert seen == ["In Progress"]
1548
+
1549
+
1550
+ def test_member_init_repr() -> None:
1551
+ seen: list[str] = []
1552
+
1553
+ class Color(Enum):
1554
+ RED = "red"
1555
+
1556
+ def __init__(self, *_args: object) -> None:
1557
+ seen.append(repr(self))
1558
+
1559
+ assert seen == ["<Color.RED: 'red'>"]
1560
+
1561
+
1562
+ def test_member_init_missing_metadata_attribute() -> None:
1563
+ seen: list[Any] = []
1564
+
1565
+ class Color(Enum):
1566
+ RED = "red"
1567
+
1568
+ def __init__(self, *_args: object) -> None:
1569
+ try:
1570
+ seen.append(self.hex)
1571
+ except AttributeError:
1572
+ seen.append(None)
1573
+
1574
+ assert seen == [None]
1575
+
1576
+
1577
+ def test_member_init_pending_attribute_not_leaked() -> None:
1578
+ class Color(Enum):
1579
+ RED = "red"
1580
+
1581
+ def __init__(self, *_args: object) -> None:
1582
+ _ = self.label
1583
+
1584
+ assert "_enumplus_pending_metadata" not in vars(Color)
1585
+
1586
+
1587
+ # ---------- _simple_enum graceful degradation ----------
1588
+
1589
+
1590
+ def test_simple_enum_members_basic_behavior() -> None:
1591
+ class _Shade:
1592
+ DARK = 1
1593
+ LIGHT = 2
1594
+
1595
+ Shade: Any = enum._simple_enum(etype=Enum)(_Shade) # type: ignore[attr-defined]
1596
+
1597
+ assert Shade.DARK.value == 1
1598
+ assert Shade.DARK.label == "Dark"
1599
+ assert Shade.LIGHT.label == "Light"
1600
+ assert Shade.DARK.metadata == {}
1601
+ assert Shade.names() == ["DARK", "LIGHT"]
1602
+ assert Shade.values() == [1, 2]
1603
+ assert Shade.choices() == [(1, "Dark"), (2, "Light")]
1604
+ assert Shade.labels() == ["Dark", "Light"]
1605
+ assert Shade.filter(unused="x") == []
1606
+ assert Shade.to_dict() == {
1607
+ "DARK": {"value": 1, "label": "Dark", "metadata": {}},
1608
+ "LIGHT": {"value": 2, "label": "Light", "metadata": {}},
1609
+ }
1610
+ assert json.loads(Shade.to_json())["name"] == "_Shade"
1611
+ with pytest.raises(AttributeError):
1612
+ _ = Shade.DARK.hex
1613
+
1614
+
1615
+ def test_simple_enum_ordered() -> None:
1616
+ class _P:
1617
+ LOW = 1
1618
+ HIGH = 2
1619
+
1620
+ P: Any = enum._simple_enum(etype=OrderedEnum)(_P) # type: ignore[attr-defined]
1621
+
1622
+ assert P.LOW < P.HIGH
1623
+ assert P.HIGH > P.LOW
1624
+ assert sorted([P.HIGH, P.LOW]) == [P.LOW, P.HIGH]
1625
+
1626
+
1627
+ # ---------- Enum member as value: equality coherence ----------
1628
+
1629
+
1630
+ def test_member_equals_its_own_enum_value() -> None:
1631
+ class Inner(Enum):
1632
+ X = "x"
1633
+ Y = "y"
1634
+
1635
+ class Outer(Enum):
1636
+ A = Inner.X
1637
+
1638
+ assert Outer.A == Inner.X
1639
+ assert Outer.A != Inner.Y
1640
+
1641
+
1642
+ def test_enum_value_equals_wrapping_member() -> None:
1643
+ class Inner(Enum):
1644
+ X = "x"
1645
+ Y = "y"
1646
+
1647
+ class Outer(Enum):
1648
+ A = Inner.X
1649
+
1650
+ assert Inner.X == Outer.A
1651
+ assert Inner.Y != Outer.A
1652
+
1653
+
1654
+ def test_contains_wrapping_member_of_enum_value() -> None:
1655
+ class Inner(Enum):
1656
+ X = "x"
1657
+ Y = "y"
1658
+
1659
+ class Outer(Enum):
1660
+ A = Inner.X
1661
+
1662
+ assert Outer.A in Inner
1663
+ assert Inner.Y not in Outer
1664
+
1665
+
1666
+ def test_from_value_wrapping_member_of_enum_value() -> None:
1667
+ class Inner(Enum):
1668
+ X = "x"
1669
+
1670
+ class Outer(Enum):
1671
+ A = Inner.X
1672
+
1673
+ assert Inner.from_value(Outer.A) is Inner.X
1674
+
1675
+
1676
+ def test_call_lookup_matches_from_value() -> None:
1677
+ class Inner(Enum):
1678
+ X = "x"
1679
+ Y = "y"
1680
+
1681
+ class Outer(Enum):
1682
+ A = Inner.X
1683
+
1684
+ assert Outer("x") is Outer.A
1685
+ assert Outer(Inner.X) is Outer.A
1686
+ with pytest.raises(ValueError):
1687
+ Outer(Inner.Y)
1688
+
1689
+
1690
+ def test_call_lookup_matches_from_value_safe_equal() -> None:
1691
+ class Weird:
1692
+ def __eq__(self, other: object) -> bool:
1693
+ raise RuntimeError("boom")
1694
+
1695
+ def __hash__(self) -> int:
1696
+ return hash("weird")
1697
+
1698
+ class C(Enum):
1699
+ A = "a"
1700
+
1701
+ assert C.from_value(Weird(), default=None) is None
1702
+ with pytest.raises(ValueError):
1703
+ C(Weird())
1704
+
1705
+
1706
+ # ---------- map() input validation ----------
1707
+
1708
+
1709
+ def test_map_rejects_non_mapping() -> None:
1710
+ class Color(Enum):
1711
+ RED = "red"
1712
+
1713
+ with pytest.raises(TypeError, match="expects a mapping"):
1714
+ Color.map([Color.RED, "x"]) # type: ignore[arg-type]
1715
+ with pytest.raises(TypeError, match="expects a mapping"):
1716
+ Color.map(None) # type: ignore[arg-type]
1717
+ with pytest.raises(TypeError, match="expects a mapping"):
1718
+ Color.map("RED") # type: ignore[arg-type]
1719
+
1720
+
1721
+ def test_map_accepts_mapping_subclass() -> None:
1722
+ from types import MappingProxyType
1723
+
1724
+ class Color(Enum):
1725
+ RED = "red"
1726
+
1727
+ proxy = MappingProxyType({Color.RED: 1})
1728
+ assert Color.map(proxy) == {"RED": 1}
1729
+
1730
+
1731
+ # ---------- Flag mixin keeps stdlib _missing_ ----------
1732
+
1733
+
1734
+ def test_flag_mixin_composite_lookup() -> None:
1735
+ class F(Enum, enum.Flag):
1736
+ A = 1
1737
+ B = 2
1738
+ C = 4
1739
+
1740
+ composite = F.A | F.B
1741
+ assert composite.value == 3
1742
+ assert F(3) is composite
1743
+ assert (F.A | F.B) & F.A is F.A
1744
+
1745
+
1746
+ def test_intflag_mixin_composite_lookup() -> None:
1747
+ class F(Enum, enum.IntFlag):
1748
+ A = 1
1749
+ B = 2
1750
+
1751
+ assert (F.A | F.B).value == 3
1752
+ assert F(3).value == 3
1753
+
1754
+
1755
+ def test_flag_mixin_strict_boundary() -> None:
1756
+ class F(Enum, enum.Flag, boundary=enum.STRICT):
1757
+ A = 1
1758
+
1759
+ with pytest.raises(ValueError):
1760
+ F(8)
1761
+
1762
+
1763
+ def test_flag_mixin_custom_missing_wins() -> None:
1764
+ class F(Enum, enum.Flag):
1765
+ A = 1
1766
+
1767
+ @classmethod
1768
+ def _missing_(cls, value: Any) -> Any:
1769
+ if value == "special":
1770
+ return cls.A
1771
+ return super()._missing_(value)
1772
+
1773
+ assert F("special") is F.A
1774
+ assert (F.A | F.A).value == 1
@@ -28,7 +28,7 @@ def test_basic_access_by_value() -> None:
28
28
  RED = "red"
29
29
  GREEN = "green"
30
30
 
31
- assert Color("red") is Color.RED # type: ignore[call-arg]
31
+ assert Color("red") is Color.RED
32
32
 
33
33
 
34
34
  def test_basic_access_by_name() -> None:
@@ -1,5 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from typing import Any, NamedTuple
4
+
3
5
  from enumplus import Enum
4
6
 
5
7
 
@@ -46,3 +48,40 @@ def test_empty_metadata_dict() -> None:
46
48
 
47
49
  assert Color.RED.value == "red" # type: ignore[comparison-overlap]
48
50
  assert Color.RED._metadata_ == {}
51
+
52
+
53
+ def test_namedtuple_value_not_unpacked() -> None:
54
+ class Point(NamedTuple):
55
+ x: int
56
+ data: dict[str, Any]
57
+
58
+ class Coord(Enum):
59
+ A = Point(1, {"label": "not metadata"})
60
+
61
+ assert Coord.A.value == Point(1, {"label": "not metadata"})
62
+ assert Coord.A._metadata_ == {}
63
+ assert Coord.A.label == "A"
64
+
65
+
66
+ def test_tuple_subclass_value_not_unpacked() -> None:
67
+ class TaggedTuple(tuple[Any, ...]):
68
+ pass
69
+
70
+ class T(Enum):
71
+ A = TaggedTuple((1, {"label": "not metadata"}))
72
+
73
+ assert T.A.value == TaggedTuple((1, {"label": "not metadata"}))
74
+ assert T.A._metadata_ == {}
75
+
76
+
77
+ def test_namedtuple_value_with_metadata_tuple() -> None:
78
+ class Point(NamedTuple):
79
+ x: int
80
+ y: int
81
+
82
+ class Coord(Enum):
83
+ A = (Point(1, 2), {"label": "Origin area"})
84
+
85
+ assert Coord.A.value == Point(1, 2) # type: ignore[comparison-overlap]
86
+ assert Coord.A._metadata_ == {"label": "Origin area"}
87
+ assert Coord.A.label == "Origin area"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes