Stranger6667 / jsonschema-rs

JSON Schema validation library
https://docs.rs/jsonschema
MIT License
482 stars 90 forks source link

Use string enums as dictionary keys #453

Open DavideCanton opened 5 months ago

DavideCanton commented 5 months ago

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:

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:

DavideCanton commented 5 months ago

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