Home > Net >  How to type hint function with a callable argument and default value
How to type hint function with a callable argument and default value

Time:07-20

I am trying to type hint the arguments of a function that takes a callable, and has a default argument (in the example below set)

from typing import Callable, List
T = TypeVar("T")
def transform(data: List[int], ret_type: Callable[[List[int]], T] = set) -> T:
    return ret_type(data)

a = [1, 2, 3]
my_set: Set = transform(a)

The above code triggers the following error message from mypy mypy3: Incompatible default for argument "ret_type" (default has type "Type[Set[Any]]", argument has type "Callable[[List[int]], T]")

What should be the correct type of ret_type ?

EDIT

The below code although not ideal works fine (cf @chepner comment)

from typing import cast, Any, Callable, TypeVar

T = TypeVar("T")

def transform(data: Any, ret_type: Callable[..., T] = cast(Callable, set)) -> T:
    return ret_type(data)

CodePudding user response:

You could use the @overload for correctly type hinting of function with default argument for your case:

from typing import Callable, List, TypeVar, overload, Set

T = TypeVar("T")

@overload
def transform(data: List[int]) -> Set[int]: ...

@overload
def transform(data: List[int], ret_type: Callable[[List[int]], T]) -> T: ...
    
# untyped implementation
def transform(data, ret_type = set):
    return ret_type(data)

a = [1, 2, 3]
my_set: Set = transform(a)
  • Related