What is the canonical way to type empty __slots__ (or empty tuple)?

Viewed 113

If I type slots:

class Foo:
    __slots__: Tuple[()] = tuple()

Then, in strict mode, mypy (0.812) tells me:

Incompatible types in assignment (expression has type "Tuple[<nothing>, ...]", variable has type "Tuple[]")

I can write:

__slots__: Tuple[()] = cast(Tuple[()], tuple())

But this is ugly. What is the canonical way to do this? What does mypy mean by Tuple[<nothing>, ...]? Tuples are immutable so surely an empty tuple shouldn't be... a variable amount of nothing..?

1 Answers

The problem is not the annotation but the value. Use a literal tuple to unambiguously represent tuples of fixed size, including the empty tuple:

class Foo:
    __slots__: Tuple[()] = ()

Note that MyPy will correctly infer the type of this __slots__ even without an annotation.


The callable tuple has a return type of Tuple[T, ...], since for most inputs the output length is not known. The call tuple() is not special cased. As with tuple() there is no value to infer T from, there is no type inhabiting T – its type is <nothing>.

Related