Skip to content

Commit

Permalink
Update Maybe typing (#325)
Browse files Browse the repository at this point in the history
Co-authored-by: Darlin Alberto <[email protected]>
  • Loading branch information
dalberto and dalberto authored Jan 5, 2024
1 parent 8893bdd commit 3b5da18
Showing 1 changed file with 6 additions and 11 deletions.
17 changes: 6 additions & 11 deletions instructor/dsl/maybe.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
from pydantic import BaseModel, Field, create_model
from typing import Type, Optional
from typing import Type, Optional, TypeVar, Generic

T = TypeVar("T", bound=BaseModel)

class MaybeBase(BaseModel):
class MaybeBase(BaseModel, Generic[T]):
"""
Extract a result from a model, if any, otherwise set the error and message fields.
"""

result: Optional[BaseModel]
result: Optional[T]
error: bool = Field(default=False)
message: Optional[str]

def __bool__(self):
return self.result is not None # type: ignore


def Maybe(model: Type[BaseModel]) -> MaybeBase:
def Maybe(model: Type[T]) -> Type[MaybeBase[T]]:
"""
Create a Maybe model for a given Pydantic model. This allows you to return a model that includes fields for `result`, `error`, and `message` for sitatations where the data may not be present in the context.
Expand Down Expand Up @@ -52,10 +53,6 @@ def __bool__(self):
MaybeModel (Type[BaseModel]): A new Pydantic model that includes fields for `result`, `error`, and `message`.
"""

class MaybeBase(BaseModel):
def __bool__(self):
return self.result is not None # type: ignore

fields = {
"result": (
Optional[model],
Expand All @@ -74,6 +71,4 @@ def __bool__(self):
),
}

MaybeModel = create_model(f"Maybe{model.__name__}", __base__=MaybeBase, **fields)

return MaybeModel # type: ignore
return create_model(f"Maybe{model.__name__}", __base__=MaybeBase, **fields)

0 comments on commit 3b5da18

Please sign in to comment.