英文:
typing.NamedTuple as type annonation for list does not work
问题
I though I could specify a type for the elements of a list as follows:
import typing
CustomType = typing.NamedTuple("CustomType", [("one", str), ("two", str)])
def test_function(some_list: list[CustomType]):
print(some_list)
if __name__ == "__main__":
test_list = list[
CustomType(one="test", two="test2"),
CustomType(one="Test", two="Test2")
]
test_function(some_list=test_list)
But this warns me, at the test_function call that Expected type 'list[CustomType]', got 'Type[list]' instead
.
The following will work, but I am not sure why it must be in this way:
test_list: list[CustomType] = list([
CustomType(one="test", two="test2"),
CustomType(one="Test", two="Test2")
])
英文:
I though I could specify a type for the elements of a list as follows:
import typing
CustomType = typing.NamedTuple("CustomType", [("one", str), ("two", str)])
def test_function(some_list: list[CustomType]):
print(some_list)
if __name__ == "__main__":
test_list = list[
CustomType(one="test", two="test2"),
CustomType(one="Test", two="Test2")
]
test_function(some_list=test_list)
But this warns me, at the test_function call that Expected type 'list[CustomType]', got 'Type[list]' instead
.
The following will work, but I am not sure why it must be in this way:
test_list: list[CustomType] = list([
CustomType(one="test", two="test2"),
CustomType(one="Test", two="Test2")
])
答案1
得分: 2
The Problem here is how you instanciate the list. list[]
will give you a list type with some extra flavour. You want to instanciate the list with the classic syntax e.g. using simply brackets, or your more convoluted list([...])
.
if __name__ == "__main__":
test_list = [
CustomType(one="test", two="test2"),
CustomType(one="Test", two="Test2")
]
test_function(some_list=test_list)
英文:
The Problem here is how you instanciate the list. list[]
will give you a list type with some extra flavour. You want to instanciate the list with the classic syntax e.g. using simply brackets, or your more convoluted list([...])
.
if __name__ == "__main__":
test_list = [
CustomType(one="test", two="test2"),
CustomType(one="Test", two="Test2")
]
test_function(some_list=test_list)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论