mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Allow Callable type hint before function definition

Open chepner opened this issue 1 year ago • 1 comments

Feature

Allow

f: Callable[[int], int]


def f(n):
    return 42

as an alternative to

def f(n: int) -> int:
    return 42

Pitch Currently, the proposed syntax produces a Name "f" already defined ... [no-redef] error, unlike similar code for non-function values:

# OK
x: int
x = 3

For some complicated function signatures, it would be clearer to provide a single Callable hint than to have argument types mixed in with the arguments themselves and the return type added after the parameter list. For that matter, the two styles above need not be mutually exclusive:

f: Callable[[int], int]
def f(n: int) -> int:
    return 42

mypy should report an error only if the types are identical. (Or perhaps compatible; I don't know if there would be use-cases for the initial type to be a supertype of the one implied by the function annotations.)

This would be consistent with the def statement being a kind of assignment, as the following is currently allowed:

x: int
x = 3

as well as eliminate the asymmetry between function parameters and "ordinary" names.

chepner avatar Feb 24 '24 15:02 chepner

This might have some tie-in to https://github.com/python/mypy/issues/2087, in that it would allow something like

class FunctionForAdmin:
    some_attribute: int

    def __call__(self, x: int) -> int:
        ...


some_function: FunctionForAdmin
def some_function(x):
    ...

some_function.some_attribute = 42

although the need for some_function to have its full type-compliant definition spread across multiple statements poses an issue.

chepner avatar Feb 24 '24 16:02 chepner

I have wanted this as a way of moving incredibly complicated overload definitions out of the way into a dedicated types file that only needs to be parsed by type checkers. I currently wrap the overloads in if TYPE_CHECKING but that still leaves them in the file, so they still add some runtime overhead, and they are really not intended for most casual readers either, harming readability.

alicederyn avatar Mar 16 '24 17:03 alicederyn