Static typing in python3: list vs List

前端 未结 1 400
既然无缘
既然无缘 2021-01-06 20:50

What is the difference between using list and List when defining for example the argument of a function in python3? For example, what is the difference between



        
1条回答
  •  囚心锁ツ
    2021-01-06 21:18

    Not all lists are the same from a typing perspective. The program

    def f(some_list: list):
        return [i*2 for i in some_list]
    
    f(['a', 'b', 'c'])
    

    won't fail a static type checker, even though it won't run. By contrast, you can specify the contents of the list using the abstract types from typing

    def f(some_list: List[int]) -> List[int]:
        return [i*2 for i in some_list]
    
    f(['a', 'b', 'c'])
    

    will fail, as it should.

    0 讨论(0)
提交回复
热议问题