Skip to content

Support for Annotated dependencies #334

@chrisguidry

Description

@chrisguidry

We're using dependencies to control most of the behavior of Docket, and the current kwarg-default style is the most useful for when you need to interact with the dependency itself:

async def high_five_customer(
    customer: int,
    db: Connection = Depends(get_connection),
):
   customer = db.query(...., customer)
   ...

But there are times when a dependency needs to refer to a parameter, like with concurrency limiting:

async def high_five_customer(
    customer: Annotated[int, ConcurrencyLimit(1)),
    db: Connection = Depends(get_connection),
):
   customer = db.query(...., customer)
   ...

This makes sure we don't look unhinged and try to high five our customers too many times at once :D (see #163).

Still further, we are hopping through some quirky type hoops to connect the type of the defaults to the type of the parameter, and Annotated gives us a cleaner way out of that as well:

async def high_five_customer(
    customer: int,
    db: Annotated[Connection, Depends(get_connection)],
):
   customer = db.query(...., customer)
   high_five(customer)

This also lets you define reusable dependencies with a little less work:

Connection = Annotated[PostgresConnection, Depends(get_connection)]

async def high_five_customer(customer: int, db: Connection):
   customer = db.query(...., customer)
   high_five(customer)

This has the benefit of allowing us to specify multiple dependencies that relate to a parameter:

async def high_five_customer(
    customer: Annotated[int, ConcurrencyLimit(1)], 
    db: Annotated[Connection, Depends(get_connection), ConcurrencyLimit(4)]
):
   customer = db.query(...., customer)
   high_five(customer)

This would express, for example, that we support 4 db connections at a time but only 1 customer at a time, for example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions