jsonschema-rs icon indicating copy to clipboard operation
jsonschema-rs copied to clipboard

Use string enums as dictionary keys

Open DavideCanton opened this issue 1 year ago • 1 comments

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?

DavideCanton avatar Feb 08 '24 17:02 DavideCanton

In any case, in my spare time I could work on it if there is interest in this feature

DavideCanton avatar Feb 08 '24 17:02 DavideCanton