Search code examples
pythontuplesmypypython-typing

Incompatible types when assigning an empty tuple to a specialised variable


I have a variable path, which should be a tuple of strings. I want to start with it set to an empty tuple, but mypy complains.

path: Tuple[str] = ()

The error is:

Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[str]")

How can I assign an empty tuple to a typed variable?

Motivation

The reason I want to do this is: I want to build up the tuple dynamically, and tuples (unlike lists) can be used as dictionary keys. For example (not what I'm actually doing):

for line in fileob:
    path += (line,)
some_dict[path] = some_object

This works well, except that mypy doesn't like the type declaration above. I could use a list and then convert it to a tuple, but it complicates the code.


Solution

  • EDIT:

    You can define a variable length, homogenous tuple like this:

    Tuple[str, ...]
    

    You can also create a "a or b" type variable with typing.Union:

    from typing import Union
    
    path: Union[Tuple[()], Tuple[str]] = ()
    
    

    OLD ANSWER:

    By trying to assign an empty tuple to a variable that you have typed to not allow empty tuples, you're effectivly missing the point of typing variables.

    I assume that the empty tuple you are trying to assign is just a token value, and that you intend to reassign the variable later in the code (to a tuple that contains only strings.)

    In that case, simply let the token value be a tuple that contains a string:

    path: Tuple[str] = ('token string',)
    

    This should stop the error message.