1

To write a maintainable code, it's a good practice to specify the input and output types as below.

def hash_a(item: object, x: int, y: int) -> int:
    return x + y

My question is how we can specify function type as the input type ? For an example,

def hash_a(funct: object, x: int, y: int) -> int:
"""
funct : is a fuction
"""
        return x + y
customcommander
  • 17,580
  • 5
  • 58
  • 84
Nipun Wijerathne
  • 1,839
  • 11
  • 13
  • 2
    Possible duplicate of [How can I specify the function type in my type hints?](https://stackoverflow.com/questions/37835179/how-can-i-specify-the-function-type-in-my-type-hints) – felipsmartins Sep 26 '19 at 15:54

2 Answers2

1

You can use typing.Callable as follows:

from typing import Callable

def hash_a(funct: Callable, x: int, y: int) -> int:
    ...

If you want to be more precise and specify the input/output types you can use Callable as a generic type as follows:

def hash_a(funct: Callable[[<arg_type_1>, <arg_type_2>, ..., <arg_type_n>], <output_type>], x: int, y: int) -> int:
    ...

whete <arg_type_1>, <arg_type_2> and <arg_type_n> represent the signature of your callable.

If you only care about the output type, you can specify an ellipsis as input types:

def hash_a(funct: Callable[..., <output_type>], x: int, y: int) -> int:
    ...
exhuma
  • 20,071
  • 12
  • 90
  • 123
0

Use typing.Callable[[int], int], where the first [int] is the type(s) of the argument(s), and the second int is the return type of the function.

blue_note
  • 27,712
  • 9
  • 72
  • 90