Skip to content

Instantly share code, notes, and snippets.

@k-saka
Created December 7, 2016 07:42
Show Gist options
  • Save k-saka/ca78139ab1f54b750ddd95669208a072 to your computer and use it in GitHub Desktop.
Save k-saka/ca78139ab1f54b750ddd95669208a072 to your computer and use it in GitHub Desktop.
callable default func
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import List, Callable, TypeVar, Optional
T = TypeVar('T')
def test(func: Callable[[str], T]) -> List[T]:
list(map(func, "1"))
print(test(str)) # OK
print(test(int)) # OK
def test1(func: Callable[[str], T]=str) -> List[T]:
# error: Incompatible types in assignment (expression has type "str", variable has type Callable[[str], T])
return list(map(func, "1"))
print(test1()) # OK
print(test1(str)) # OK
print(test1(int)) # OK
def _to_str(elem: str) -> str:
return str(elem)
def test2(func: Callable[[str], T]=_to_str) -> List[T]:
# error: Incompatible types in assignment (expression has type Callable[[str], str], variable has type Callable[[str], T])
return list(map(func, "1"))
print(test2()) # OK
print(test2(str)) # OK
print(test2(int)) # OK
def test3(func: Callable[[str], str]=str) -> List[str]:
return list(map(func, "1"))
print(test3()) # OK
print(test3(str)) # OK
print(test3(int)) # OK cause error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment