简体   繁体   English

根据类型在列表上使用 tuple() 不会返回相同的元组

[英]using tuple() on a list does not return an identical tuple according to typing

I created a class with a list attribute containing an int and a float.我创建了一个 class ,其列表属性包含一个 int 和一个 float。 I then tried creating a getter method to return the list as a tuple.然后我尝试创建一个 getter 方法以将列表作为元组返回。

from typing import Tuple, List

class MyClass:
    def __init__(self):
        self.__lst = [3, 5.0]

    def get_lst_as_tup(self) -> Tuple[int, float]:
        return tuple(self.__lst)

while it seems to work properly, PyCharm presents a problem:虽然它似乎工作正常,但 PyCharm 出现了一个问题:

Expected type 'Tuple[int, float]', got 'Tuple[Union[int, float], ...]' instead

after seeking stack overflow I tried several other implementations for the return statement.在寻求堆栈溢出后,我为 return 语句尝试了其他几种实现。 that resulted in the same error:这导致了同样的错误:

return (element for element in self.__lst)

return tuple(element for element in self.__lst)

return (*self.__lst,) this specific implementation resulted in: return (*self.__lst,)这个特定的实现导致:

Expected type 'Tuple[int, float]', got 'Tuple[Any]' instead

I was able to get rid of the error by using return self.__lst[0], self.__lst[1]我能够通过使用return self.__lst[0], self.__lst[1]摆脱错误

but I do not understand why it does not accept the other implementations.但我不明白为什么它不接受其他实现。

Notes: I did not use the word tuple elsewhere in the file.注意:我没有在文件的其他地方使用元组这个词。 This error occures even when this is all there is in the file.即使文件中只有这些,也会发生此错误。

For your example对于你的例子

return (element for element in self.__lst)

I doubt that you got the same error as this in fact returns a generator and not a tuple.我怀疑您是否遇到与 this 实际上返回生成器而不是元组相同的错误。

Your other attempts你的其他尝试

return tuple(self.__lst)
return (*self.__lst,)
return tuple(element for element in self.__lst)

are all valid approaches to convert the list self.__lst into a tuple.都是将列表self.__lst转换为元组的有效方法。 Of course, the most readable is tuple(self.__lst) , so you should probably stick with this.当然,最易读的是tuple(self.__lst) ,所以你应该坚持这个。

I think the suggested type Tuple[Union[int, float], ...] is still too narrow here.我认为这里建议的类型Tuple[Union[int, float], ...]仍然太窄。 You are converting a list which is of variable length into a tuple.您正在将可变长度的列表转换为元组。 There is no way of knowing which length self.__lst will have in your program.无法知道self.__lst在您的程序中的长度。 Consider this:考虑一下:

m = MyClass()
m._MyClass__lst.append("hello")
r = m.get_lst_as_tup()
print(r)

Output: (3, 5.0, 'hello') Output: (3, 5.0, 'hello')

Which is of type Tuple[int, float, str] .这是Tuple[int, float, str]类型。

However, when you use return self.__lst[0], self.__lst[1] it is guaranteed that the function will return a tuple of length 2 (or throw an exception if the list became smaller than length 2).但是,当您使用return self.__lst[0], self.__lst[1]时,可以保证 function 将返回长度为 2 的元组(如果列表小于长度 2,则抛出异常)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM