Incompatible types when assigning an empty tuple to a specialised variable

后端 未结 1 553
灰色年华
灰色年华 2021-01-18 05:08

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]          


        
1条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 06:08

    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.

    0 讨论(0)
提交回复
热议问题