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

Generate Annotated types instead of root types for string constraints #2018

Open
RonnyPfannschmidt opened this issue Jun 28, 2024 · 0 comments

Comments

@RonnyPfannschmidt
Copy link

Is your feature request related to a problem? Please describe.

given a schema like

components:
  schemas:
    HereBeDragons:
      type: string
      pattern: here
    PassMe:
      type: object
      properties:
        mangled_string:
          anyOf:
            - $ref: '#/components/schemas/PettyNumber'
            - $ref: '#/components/schemas/HereBeDragons'
    PettyNumber:
      type: string
      pattern: '[0-9]{2,8}'
  

multiple root types are created and in turn create object indirection

from pydantic import BaseModel, Field, RootModel, constr


class HereBeDragons(RootModel[constr(pattern=r"here")]):
    root: constr(pattern=r"here")


class MoreValues(BaseModel):
    name: str
    age: int | None = None


class PettyNumber(RootModel[constr(pattern=r"[0-9]{2,8}")]):
    root: constr(pattern=r"[0-9]{2,8}")

class PassMe(BaseModel):
    mangled_string: PettyNumber | HereBeDragons | None = None
  

Describe the solution you'd like

decare the types more directly like

# using python 3.12+ syntax

from pydantic import BaseModel, Field, StringConstraints


type HereBeDragons = Annotated[str, StringConstraints(pattern=r"here")]
type PrettyNumber = Annotated[str, StringConstraints(pattern=r"[0-9]{2,8}")]


class PassMe(BaseModel):
    mangled_string: PettyNumber | HereBeDragons | None = None

Additional context
Add any other context or screenshots about the feature request here.

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

No branches or pull requests

1 participant