Currently, a string enum cannot be used as the key of an object.
from enum import Enum, StrEnum
from jsonschema_rs import is_valid
schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": False,
"properties": {
"foo": {"type": "number"},
"baz": {"type": "number"},
},
"required": ["foo", "baz"],
"type": "object",
}
class MyEnum(str, Enum):
foo = "foo"
bar = "baz"
# this works
print(is_valid(schema, {"foo": 1, "baz": 2}))
# this works too
print(is_valid(schema, {MyEnum.foo.value: 1, MyEnum.bar.value: 2}))
# this raises a ValueError: Dict key must be str. Got 'MyEnum'
print(is_valid(schema, {MyEnum.foo: 1, MyEnum.bar: 2}))
To me, it seems a valid use case of a string enum, since:
enums in values are supported by the library
string enums should always have a string value property.
I've tried with the 3.11 StrEnum type, that guarantees that str(MyEnum.foo) == "foo", but it doesn't work either (probably because I saw an explicity check on the type of the key to be exactly str).
Is it feasible to:
for classes that subclass (str, Enum) to use their value property
for classes that subclass StrEnum to use their __str__ representation?
Currently, a string enum cannot be used as the key of an object.
To me, it seems a valid use case of a string enum, since:
value
property.I've tried with the 3.11
StrEnum
type, that guarantees thatstr(MyEnum.foo) == "foo"
, but it doesn't work either (probably because I saw an explicity check on the type of the key to be exactly str).Is it feasible to:
(str, Enum)
to use theirvalue
propertyStrEnum
to use their__str__
representation?