Incompatible types when assigning an empty tuple to a specialised variable

感情迁移 提交于 2020-05-09 03:30: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] = ()

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.


回答1:


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.



来源:https://stackoverflow.com/questions/57566353/incompatible-types-when-assigning-an-empty-tuple-to-a-specialised-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!