Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use string enums as dictionary keys #453

Open
DavideCanton opened this issue Feb 8, 2024 · 1 comment
Open

Use string enums as dictionary keys #453

DavideCanton opened this issue Feb 8, 2024 · 1 comment

Comments

@DavideCanton
Copy link

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants