Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import collections
import enum
import inspect
import itertools
import re
Expand Down Expand Up @@ -226,6 +227,8 @@ def _compile(self, schema):
return self._compile_tuple(schema)
elif isinstance(schema, (frozenset, set)):
return self._compile_set(schema)
elif isinstance(schema, enum.Enum):
return _compile_scalar(schema)
type_ = type(schema)
if inspect.isclass(schema):
type_ = schema
Expand Down
23 changes: 23 additions & 0 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1869,6 +1869,29 @@ class StringChoice(str, Enum):
string_schema("hello")


def test_enum_as_schema():
"""Test enum members can be used as scalar schemas and mapping keys."""

class Choice(Enum):
Easy = 1
Hard = 3

class StringChoice(str, Enum):
Easy = 'easy'
Hard = 'hard'

# As a scalar schema, an enum member is matched by equality.
schema = Schema(Choice.Easy)
assert schema(Choice.Easy) == Choice.Easy
with raises(Invalid, 'not a valid value'):
schema(Choice.Hard)

# As a mapping key, including default handling for missing keys.
dict_schema = Schema({Optional(StringChoice.Easy, default=True): bool})
assert dict_schema({}) == {StringChoice.Easy: True}
assert dict_schema({'easy': False}) == {'easy': False}


class MyValueClass(object):
def __init__(self, value=None):
self.value = value
Expand Down
Loading