Skip to content

Type inference regression with sort and cmp_to_key #9372

Closed

Description

@JukkaL

This code fragment started generating errors after 0.780 release:

from functools import cmp_to_key

x = [(1, '')]

def f(): pass

reveal_type(cmp_to_key)

x.sort(key=cmp_to_key(lambda x, y: f()))  # Cannot infer type argument 1 of "cmp_to_key"

It might be related to python/typeshed#4192.

This happens only about 3 times in a big Dropbox internal codebase, and this is infrequent enough that I don't consider it release-blocking. I'm marking it as high-priority since this is a regression.

Activity

  1. hauntsaninja commented on Aug 29, 2020

    @hauntsaninja
    Collaborator

    Can confirm that python/typeshed#4192 is the trigger for this to start generating errors. (Just pushed python/typeshed#4492 which improves the return type of cmp_to_key, but doesn't affect this).

    Here's a self contained, mostly minimised repro:

    from typing import *
    
    T = TypeVar("T")
    
    def ctk(f: Callable[[T, T], int]) -> Callable[[T], Any]: ...
    
    @overload
    def sortedx(__iterable: Iterable[str], *,
                key: None = ...) -> List[str]: ...
    @overload
    def sortedx(__iterable: Iterable[T], *,
                key: Callable[[T], int]) -> List[T]: ...
    
    def sortedx(*args, **kwargs): ...
    
    reveal_type(sortedx([1,2,3], key=ctk(lambda x, y: 5)))
    

    If you remove the overload, the error goes away.

  2. ilevkivskyi commented on Feb 5, 2025

    @ilevkivskyi
    Member

    Both original and self-contained examples now pass correctly.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions