Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

Closed
bruno-f-cruz opened this issue Sep 6, 2024 · 2 comments · Fixed by #94
Closed

A potential solution for improving enum-like classes #73

bruno-f-cruz opened this issue Sep 6, 2024 · 2 comments · 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:

@bruno-f-cruz
Copy link
Author

Was this intended to be closed?
I don't think that any of the points in the issue were address by the referenced PR (?)

If you are using the issues as a ticketing system I feel moving this to a discussion feels more appropriate if you don't want to track it.

@dbirman dbirman reopened this Nov 6, 2024
@dbirman
Copy link
Member

dbirman commented Nov 6, 2024

Nope just a mistake, but yes this should probably be a discussion.

@AllenNeuralDynamics AllenNeuralDynamics locked and limited conversation to collaborators Jan 6, 2025
@dbirman dbirman converted this issue into discussion #121 Jan 6, 2025

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants