Skip to content

Commit 8e52b3f

Browse files
committed
Add str enum checker: validate string is a valid member
When the annotation is a str-based Enum subclass (e.g. spacy.lang.zh.Segmenter), accept plain strings that are valid enum member values and reject invalid ones with a helpful error.
1 parent 93da254 commit 8e52b3f

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

confection/validation.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import collections.abc
88
import inspect
99
import sys
10+
from enum import Enum
1011
from pathlib import PurePath
1112
from types import GeneratorType
1213
from typing import Any, Optional, get_type_hints
@@ -419,6 +420,15 @@ def _has_strict_extras(extras):
419420
)
420421

421422

423+
def _confection_str_enum_checker(value, origin_type, args, memo):
424+
"""Checker for str enums — accept a string if it's a valid member value."""
425+
try:
426+
origin_type(value)
427+
except (ValueError, KeyError):
428+
members = ", ".join(repr(m.value) for m in origin_type)
429+
raise _TypeCheckError(f"is not a valid {origin_type.__name__}: expected one of {members}")
430+
431+
422432
def _confection_checker_lookup(origin_type, args, extras):
423433
"""Lookup function registered with typeguard that intercepts types
424434
confection handles specially — plain scalars with coercion, pydantic
@@ -439,6 +449,9 @@ def _confection_checker_lookup(origin_type, args, extras):
439449
return _confection_leaf_checker
440450
if isinstance(origin_type, type) and issubclass(origin_type, Schema):
441451
return _confection_schema_checker
452+
# str enums — accept plain strings that are valid members
453+
if isinstance(origin_type, type) and issubclass(origin_type, str) and issubclass(origin_type, Enum):
454+
return _confection_str_enum_checker
442455
# Pydantic types with validator hooks (e.g. pydantic.v1.types.PositiveInt)
443456
if isinstance(origin_type, type) and (
444457
hasattr(origin_type, "__get_validators__")

0 commit comments

Comments
 (0)