Skip to content

Limited inference with union of callables and assignment to a union #18191

Open

Description

@Viicos

Bug Report

Apologies if this was raised already. The only related issue I could find is #15887.

In Pydantic 2.10, we changed the definition of our field function to be:

from typing import Callable, TypeVar

_T = TypeVar('_T')

def Field(
    *,
    default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
) -> _T: ...

While this type checks correctly for some common use cases, we get errors when the Field function is assigned to a union of types, or when the default factory signature isn't trivial (e.g. contains overloads). Here are some examples failing:

(playground)

EDIT: Seems like the issue was fixed since 1.16.0. The issue with Class.b remains:

cvar = ContextVar[None]("session_id", default=None)


class Class:
    # error: Argument "default_factory" to "Field" has incompatible type "type[list[Any]]"; expected "Callable[[], Never] | Callable[[dict[str, Any]], Never]"  [arg-type]:
    a: list | None = Field(default_factory=list)

    # error: Argument "default_factory" to "Field" has incompatible type overloaded function; expected "Callable[[], Never] | Callable[[dict[str, Any]], Never]"  [arg-type]:
    b: None = Field(default_factory=cvar.get)  # note that `cvar.get` is overloaded. The first overload (`() -> None`) should match.


    # fine:
    fine: list = Field(default_factory=list)

Note that (at least for a), this worked as expected with the old type inference.

I first wanted to know if this can be considered a mypy limitation, or is the code really unsafe in some way? Or maybe is it because the typing spec does not provide any info regarding these use cases?

In comparison, pyright and pyre accepts the provided examples. We will currently recommend users to add a type: ignore comment and redirect to this issue. However, feel free to close if there's already an issue tracking this.

Thanks in advance

Your Environment

  • Mypy version used: 1.13
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.13

Activity

  1. pcastellazzi commented on May 17, 2025

    @pcastellazzi

    I am not 100% sure is related, but the following code produces a similar error. The idea is to use the outer function as a parameter for a decorator, similar to what functools.wraps do. From my limited testing, it seems the error arises from State being a union type and nested Callables being involved.

    from typing import Callable
    
    class Failure[F]: error: F
    class Success[S]: value: S
    type State[F, S] = Failure[F] | Success[S]
    
    type InnerFn[F, S] = Callable[[], State[F, S]]
    type WrapperFn[F, S] = Callable[[InnerFn[F, S]], InnerFn[F, S]]
    type CallerFn[F, S] = Callable[..., InnerFn[F, S]]
    
    def decorator_with_argument[F, S](caller: CallerFn[F, S]) -> WrapperFn[F, S]:
        def wrapper(fn: InnerFn[F, S]) -> InnerFn[F, S]:
            return fn
        return wrapper
    
    def outer_function1[F, S](state: State[F, S]) -> InnerFn[F, S]:
        @decorator_with_argument(outer_function1)
        def inner_function() -> State[F, S]:
            return state
    
        return inner_function

    MyPy produces the following errors:

    main.py:17: error: Argument 1 has incompatible type "Callable[[], Failure[F] | Success[S]]"; expected "Callable[[], Failure[Never] | Success[Never]]"  [arg-type]
    main.py:24: error: Argument 1 has incompatible type "Callable[[], Failure[str] | Success[str]]"; expected "Callable[[], Failure[Never] | Success[Never]]"  [arg-type]
    Found 2 errors in 1 file (checked 1 source file)
    

    Playground link: https://mypy-play.net/?mypy=latest&python=3.12&gist=6a93abe464faa4f20505341e99a3dd49.

  2. marek-elisity commented on Sep 23, 2025

    @marek-elisity

    Update mypy :)

  3. Viicos commented on Sep 23, 2025

    @Viicos
    ContributorAuthor

    Seems like the issue for Class.a got fixed in 1.16.0. Great! Class.b still raises an error on latest though.

  4. pcastellazzi commented on Sep 23, 2025

    @pcastellazzi

    @marek-elisity, @Viicos My example still fails in 1.18.2 in python 3.12, 3.13 and 3.14.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions