python / python/mypy

Allow Callable type hint before function definition

Open
#16,946 2 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no file, test, or entry point. Start by locating mypy's handling of annotated assignments and function definitions, then compare how it reports duplicate names. Done means the Callable declaration before def is accepted, compatible annotations are handled consistently, and conflicting types still produce an error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.