将空元组分配给专用变量时的类型不兼容 [英] Incompatible types when assigning an empty tuple to a specialised variable

查看:44
本文介绍了将空元组分配给专用变量时的类型不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量 path,它应该是一个字符串元组.我想从它设置为一个空元组开始,但 mypy 抱怨.

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] = ()

错误是:

赋值中的类型不兼容(表达式类型为Tuple[]",变量类型为Tuple[str]")

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

如何将空元组分配给类型化变量?

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

我想这样做的原因是:我想动态地建立元组,元组(与列表不同)可以用作字典键.例如(不是我实际在做的):

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

这很有效,只是 mypy 不喜欢上面的类型声明.我可以使用列表,然后将其转换为元组,但这会使代码复杂化.

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.

推荐答案

您可以定义一个可变长度、同质元组,例如这个:

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

Tuple[str, ...]

您还可以使用 <创建a 或 b"类型变量代码>typing.Union:

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

from typing import Union

path: Union[Tuple[()], Tuple[str]] = ()

旧答案:

通过尝试将空元组分配给您输入的不允许空元组的变量,您实际上错过了输入变量的要点.

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.

这篇关于将空元组分配给专用变量时的类型不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆