typing.NamedTuple 作为列表的类型注释不起作用。

huangapple go评论66阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年5月24日 18:04:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定