Skip to content

Union between a callable and a type not respected by functools.partial #17741

Closed

Description

@eli-schwartz

Seems similar to #17646 but not fixed in https://mypy-play.net/?mypy=master&python=3.12
The linked #17659 is not applicable because I am not using Self.

Sample code:

import functools
import typing as T
from typing_extensions import TypeAlias

FooBarFunc: TypeAlias = T.Callable[..., 'FooBar']

class FooBar:
    def __init__(self, arg1: str) -> None:
        pass

def transform(t: T.Union[T.Type[FooBar], FooBarFunc]) -> None:
    val = functools.partial(t)

Error:

main.py:12: error: "type[FooBar] | Callable[..., FooBar]" not callable  [misc]

The codebase where this was discovered: https://github.com/mesonbuild/meson/blob/83f8de5357f31d6448ae033e1e8ed2b22c8c306a/mesonbuild/dependencies/factory.py#L75-L95

mesonbuild/dependencies/factory.py:95:38: error: "type[CMakeDependency] | Callable[..., CMakeDependency]" not callable  [misc]

Both sides of the union if cast and used independently, work.

Activity

  1. hauntsaninja commented on Oct 8, 2024

    @hauntsaninja
    Collaborator

    This is sort of underlying behaviour in mypy that is exposed now that mypy checks functools.partial

    E.g. on mypy 1.11 both of these will complain

    def join(t1: T.Type[FooBar], t2: FooBarFunc):
        val1 = [t1, t2]
        val1[0]("asdf")
        
        val2 = t1 if random.random() < 0.5 else t2
        val2("asdf")
    

    This could be fixed by improving the join logic (improving callable joins would fix many existing mypy issues) or potentially by changing the functools.partial logic to avoid using joins on unions (this could get messy)

  2. self-assigned this
    on Oct 9, 2024
  3. added a commit that references this issue on Oct 9, 2024
    662b1bd
  4. eli-schwartz commented on Oct 9, 2024

    @eli-schwartz
    ContributorAuthor

    Thanks! I've tested mypy from git and there is one less error report now when upgrading mypy (and looks like the others are all either our fault, unused "type: ignore", or a renamed error code). <3

  5. added a commit that references this issue on Oct 9, 2024
    eca206d
  6. added a commit that references this issue on Oct 10, 2024
    2e38965
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugmypy got something wrong

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions