在 MyPy 中定义可选容器类型参数类型的正确方法

Correct way to define types of optional container-type arguments in MyPy

Python 中可选容器类型参数的约定如下:

def f(lst=None):
   if lst is None:
      lst = []
   ...

我的代码中有很多这种模式,以避免列表、字典或任何为函数全局定义的问题,如果下游的某些东西改变了全局对象就会出现问题。

这很好用,但现在我正在向我的代码的某些部分添加静态类型检查,我想知道在此处添加它们的最佳方式是什么。 lst 在定义为关键字参数时必须具有 Optional[List[T]] 类型,但在初始检查后它应该具有 List[T] 作为类型。我无法在声明后重新定义 lst 的类型,并且创建新参数似乎会添加不必要的代码行并且容易造成混淆。对此模式进行类型检查的最佳方法是什么?

有趣的问题。显然,mypy 足够聪明,可以理解您从 OptionalList 所做的切换。请参阅此代码:

从键入 import Union, Optional, List

def bar(lst: List):
    print("Bar")
    print(lst)

def foo(lst:Optional[List] = None):
    if lst is None:    # Removing these two lines
        lst = []       # results in a type mismatch error
    print(lst)
    bar(lst)           # this is okay. mypy understands that lst is a 'List' 

foo([1, 2, "x"])      # Okay 
foo(None)             # okay
foo("some string")    # error, of course