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

proper enum schema for pydantic #651

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

jbkoh
Copy link

@jbkoh jbkoh commented Dec 9, 2024

Summary

Checklist

  • If code changes were made then they have been tested.
    • I have updated the documentation to reflect the changes.
  • This PR fixes an issue.
  • This PR adds something new (e.g. new method or parameters).
    • This change has an associated test.
  • This PR is a breaking change (e.g. methods or parameters removed/renamed)
    • It might be breaking anybody using int instead of Enum when using pydantic, though I don't think that's desired.
  • This PR is not a code change (e.g. documentation, README, ...)

@jbkoh
Copy link
Author

jbkoh commented Dec 9, 2024

just added a test too.

@jbkoh
Copy link
Author

jbkoh commented Dec 9, 2024

@Gobot1234 please review and let me know if it's in the right direction.

@@ -17,7 +17,16 @@ class {{ enum.py_name }}(betterproto.Enum):
def __get_pydantic_core_schema__(cls, _source_type, _handler):
from pydantic_core import core_schema

return core_schema.int_schema(ge=0)
def validate(value: int) -> "{{ enum.py_name }}":
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having a function for each of these adds a lot of bulk to the generated files, can this not go in the original definition for Enum and also be inlined into a lambda as this doesn't need type hints?

Copy link
Author

@jbkoh jbkoh Dec 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with the suggestion. Where do you recommend to declare the validate function? We can also define it as a method in betterproto library too.

Copy link
Author

@jbkoh jbkoh Dec 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something like

def get_validate_betterproto_enum(cls):
  def validate(cls, value): 
    return cls(value)
  return validate

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 this pull request may close these issues.

2 participants