How to type hint a tuple of callables when the default is empty

Viewed 384

I'm type hinting like this:

some_kwarg: Tuple[Callable] = ()

but mypy raises

error: Incompatible default for argument "some_kwarg" (default has type "Tuple[]", argument has type "Tuple[Callable[..., Any]]")

I wouldn't want to put a dummy callable in the default kwarg so what's the right thing to do?

2 Answers

You are type annotating it to accept a tuple of size exactly 1. Use:

Tuple[Callable, ...]

To indicate a homogeneous tuple of any size.

It looks like your parameter is optional so you could use Optional from typing. I use the following and mypy diden't find any issues.

from typing import Tuple, Optional, Callable
def test_fun(some_kwarg: Optional[Tuple[Callable]]=None):
    pass
Related