【发布时间】:2022-10-12 22:35:07
【问题描述】:
我有一个函数可以在列表中的单个列或一对列上创建 pyspark WindowSpec 分区,具体取决于布尔参数。 Mypy 抛出一个我无法理解的错误,因为我的参数partition_cols 应该是Union[str, List[str]],这对于Window.partitionBy() 是可以接受的。
示例方法和错误:
from pyspark.sql import Window, WindowSpec
def get_window(single_column: bool) -> WindowSpec:
partition_cols = "key" if single_column else ["key", "name"]
return Window.partitionBy(partition_cols).orderBy("timestamp").rangeBetween(0, 10)
然后运行 mypy:
$ mypy tmp.py
tmp.py:8: error: Argument 1 to "partitionBy" of "Window" has incompatible type "Sequence[str]"; expected "Union[Union[Column, str], List[Union[Column, str]]]" [arg-type]
【问题讨论】:
-
哇,在 pyspark 中这是一个非常糟糕的设计决定。首先,
list是不变的,因此即使list[str]也不允许用于此功能,因此只有解包是一个有效选项。它还检查isinstance(..., list),因此您不能传递tuple和其他序列(至少),甚至可能在这里支持set。这很尴尬:要么否认这种情况(只允许*str),要么适当地支持它,list不是python中唯一的序列!
标签: python pyspark mypy python-typing