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

A potential solution for improving enum-like classes #73

Open
bruno-f-cruz opened this issue Sep 6, 2024 · 0 comments · May be fixed by #94
Open

A potential solution for improving enum-like classes #73

bruno-f-cruz opened this issue Sep 6, 2024 · 0 comments · May be fixed by #94

Comments

@bruno-f-cruz
Copy link

After a brainstorming session with @jtyoung84 , we came up with this idea:

from pydantic import BaseModel, RootModel, Field
from typing import Annotated, List, Literal, Union, ClassVar, Dict

class _Base(BaseModel):
    key: str
    a: int

    def __hash__(self) -> int:
        return hash(self.key)


class _Foo(_Base):
    key: Literal["Foo"] = "Foo"
    a: int = 1

class _Bar(_Base):
    key: Literal["Bar"] = "Bar"
    a: int = 2 


class MyClass(RootModel):
    root: Annotated[Union[_Foo, _Bar], Field(..., discriminator="key")]
    ONE_OF: ClassVar[Annotated[Union[_Foo, _Bar], Field(..., discriminator="key")]] = Annotated[Union[_Foo, _Bar], Field(..., discriminator="key")]
    Foo: ClassVar[_Foo] = _Foo()
    Bar: ClassVar[_Bar] = _Bar()


class Container(BaseModel):
    prop_to_be_deprecated: MyClass.ONE_OF
    prop: MyClass
    dict_of_prop: Dict[MyClass.ONE_OF, int] # This doesn't work :(

new = Container(
        prop_to_be_deprecated=MyClass.Bar,
        prop=MyClass.Foo,
        dict_of_prop={MyClass.Foo: 1})

# However this works :D
a = {}
a[_Foo()] = 1
a[_Bar()] = 2

print(a[_Bar()])

This would solve a few problems. Namely:

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

Successfully merging a pull request may close this issue.

1 participant