Skip to content

feat: extend type ergonomics to response types #105

@bokelley

Description

@bokelley

Summary

PR #103 added excellent type ergonomics for request types (enum coercion, dict→typed coercion, etc.). This follow-up requests extending similar ergonomics to response types.

Problem

When constructing response objects, library consumers face the same friction that existed with requests:

1. List variance with subclasses

from adcp import GetProductsResponse, Product

# Our schema extends Product with internal fields
class OurProduct(Product):
    internal_config: dict | None = Field(default=None, exclude=True)

# This works at runtime but fails mypy
products: list[OurProduct] = [OurProduct(id="1", name="Test")]
response = GetProductsResponse(products=products)  # Type error: list[OurProduct] not assignable to list[Product]

We currently work around this with cast():

response = GetProductsResponse(products=cast(list[Product], products))

2. Dict coercion for response fields

Response types with context or ext fields require explicit construction:

# Current (verbose)
response = GetProductsResponse(
    products=products,
    context=ContextObject(request_id="123")
)

# Desired (ergonomic)
response = GetProductsResponse(
    products=products,
    context={"request_id": "123"}
)

Affected Response Types

  • GetProductsResponse (products list, context)
  • GetCreativesResponse (creatives list, context)
  • ListCreativeFormatsResponse (formats list, context)
  • CreateMediaBuyResponse (packages list, context)
  • GetMediaBuyDeliveryResponse (context)
  • Any other response types with list fields or context/ext

Proposed Solution

Apply the same BeforeValidator pattern from #103 to response types:

  1. List fields: Accept list[Subclass] and coerce to list[BaseType]
  2. Context/ext fields: Accept dict and coerce to ContextObject

Benefits

  • Removes need for cast() calls in consumer code
  • Consistent API between request and response construction
  • Better developer experience when building adapters/servers

Related

🤖 Generated with Claude Code

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions