Infer type of generic class from return type of (optionally awaitable) callable passed to constructor
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
I've confirmed the following works in pyright and pyrefly - but not in mypy:
from dataclasses import dataclass
from typing_extensions import (
Awaitable,
Callable,
Generic,
TypeVar,
assert_type,
)
T = TypeVar("T")
@dataclass
class Agent(Generic[T]):
output_type: Callable[..., T] | Callable[..., Awaitable[T]]
async def coro() -> bool:
return True
def func() -> int:
return 1
# works
assert_type(Agent(func), Agent[int])
# mypy - error: Argument 1 to "Agent" has incompatible type "Callable[[], Coroutine[Any, Any, bool]]"; expected "Callable[..., Never] | Callable[..., Awaitable[Never]]" [arg-type]
coro_agent = Agent(coro)
# pyright, pyrefly - works
# mypy - error: Expression is of type "Agent[Any]", not "Agent[bool]"
assert_type(coro_agent, Agent[bool])
# works
assert_type(Agent[bool](coro), Agent[bool])
I want T to be inferred as the ultimate return type of the awaitable if an async function is passed rather than a regular one, but I suppose it's ambiguous which side of the union is the best match.
It would be great to see this work in mypy, but I'm also open to suggestions to do this in a less ambiguous way!
- This is related to a new PydanticAI feature, if you're curious check out https://github.com/pydantic/pydantic-ai/pull/1785#issuecomment-2905774110
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running mypy on the provided dataclass, generic, and callable reproduction, then trace the type-inference path for Agent(coro) versus Agent(func). Compare the inferred type with the expected Agent[bool] and consider how the union of regular and awaitable callables should be resolved; done means the reproduction passes without requiring an explicit type argument.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100