Use Enum membership rules without coercing arbitrary input
Enum membership answers a specific question: whether an enum member belongs to an enum class. It is not a general-purpose parser for arbitrary input. is_declared_mode() therefore checks isinstance(candidate, Mode) before evaluating candidate in Mode. The guard means the membership operation receives an actual Mode member, while strings, numbers, and unrelated objects simply return False without being converted.
The concrete member Mode.PREVIEW passes both checks. The raw string "preview" is rejected even though it equals that member’s .value; no call such as Mode(candidate) attempts value coercion. This distinction is useful when a function’s contract accepts already-validated domain objects rather than wire values. A separate parser can deliberately call Mode(raw) and handle ValueError when converting known textual input.
Python 3.12 changed enum-class containment so that raw values can return true for value in EnumClass. The instance guard keeps this function’s result independent of that widening and is compatible with earlier Python versions too. See the official enum documentation for containment semantics and the Python 3.12 version change. These assertions establish only this predicate’s behavior, not that an accepted member is appropriate for a particular workflow.
AI-assistance disclosure: this article was drafted with AI assistance and should be aligned with the application’s input contract.
from enum import Enum
class Mode(str, Enum):
PREVIEW = "preview"
FINAL = "final"
def is_declared_mode(candidate: object) -> bool:
return isinstance(candidate, Mode) and candidate in Mode
assert is_declared_mode(Mode.PREVIEW)
assert not is_declared_mode("preview")
assert not is_declared_mode(1)
print(
f"member={is_declared_mode(Mode.PREVIEW)} "
f"raw={is_declared_mode('preview')}"
)
member=True raw=False
Comments
Post a Comment