Skip to content

fix(types): handle more discriminated union shapes #137

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

Merged
merged 1 commit into from
Mar 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/browserbase/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
from ._constants import RAW_RESPONSE_HEADER

if TYPE_CHECKING:
from pydantic_core.core_schema import ModelField, LiteralSchema, ModelFieldsSchema
from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema

__all__ = ["BaseModel", "GenericModel"]

Expand Down Expand Up @@ -646,15 +646,18 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,

def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
schema = model.__pydantic_core_schema__
if schema["type"] == "definitions":
schema = schema["schema"]

if schema["type"] != "model":
return None

schema = cast("ModelSchema", schema)
fields_schema = schema["schema"]
if fields_schema["type"] != "model-fields":
return None

fields_schema = cast("ModelFieldsSchema", fields_schema)

field = fields_schema["fields"].get(field_name)
if not field:
return None
Expand Down
32 changes: 32 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,3 +854,35 @@ class Model(BaseModel):
m = construct_type(value={"cls": "foo"}, type_=Model)
assert isinstance(m, Model)
assert isinstance(m.cls, str)


def test_discriminated_union_case() -> None:
class A(BaseModel):
type: Literal["a"]

data: bool

class B(BaseModel):
type: Literal["b"]

data: List[Union[A, object]]

class ModelA(BaseModel):
type: Literal["modelA"]

data: int

class ModelB(BaseModel):
type: Literal["modelB"]

required: str

data: Union[A, B]

# when constructing ModelA | ModelB, value data doesn't match ModelB exactly - missing `required`
m = construct_type(
value={"type": "modelB", "data": {"type": "a", "data": True}},
type_=cast(Any, Annotated[Union[ModelA, ModelB], PropertyInfo(discriminator="type")]),
)

assert isinstance(m, ModelB)