Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Callable type hint before function definition #16946

Open
chepner opened this issue Feb 24, 2024 · 2 comments
Open

Allow Callable type hint before function definition #16946

chepner opened this issue Feb 24, 2024 · 2 comments
Labels

Comments

@chepner
Copy link

chepner commented Feb 24, 2024

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
Copy link
Author

chepner commented Feb 24, 2024

This might have some tie-in to #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.

@alicederyn
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants