简体   繁体   English

mypy 无法正确推断生成器理解的类型

[英]mypy cannot infer type of generator comprehension correctly

I am using the stub files provided by data-science-types to have mypy be able to check my pandas related code.我正在使用data-science-types提供的存根文件让 mypy 能够检查我的 Pandas 相关代码。 Sadly I get the following behaviour:可悲的是,我得到以下行为:

For为了

import pandas as pd

def test() -> pd.DataFrame:
    pass

pd.concat((test() for _ in range(10)))

mypy reports test.py:6: error: Argument 1 to "concat" has incompatible type "Generator[DataFrame, None, None]"; expected "Union[Sequence[DataFrame], Mapping[str, DataFrame]]". mypy 报告test.py:6: error: Argument 1 to "concat" has incompatible type "Generator[DataFrame, None, None]"; expected "Union[Sequence[DataFrame], Mapping[str, DataFrame]]". test.py:6: error: Argument 1 to "concat" has incompatible type "Generator[DataFrame, None, None]"; expected "Union[Sequence[DataFrame], Mapping[str, DataFrame]]". If I use pd.concat([test() for _ in range(10)]) instead mypy is happy again.如果我使用pd.concat([test() for _ in range(10)])而不是 mypy 又高兴了。 Can somebody explain to me what's going on there?有人可以向我解释那里发生了什么吗?

Just in case it's relevant.以防万一。 I am using python3.8.5, pandas 1.1.2, mypy 0.782 and data-science-types 0.2.18.我正在使用 python3.8.5、pandas 1.1.2、mypy 0.782 和 data-science-types 0.2.18。

You are confusing a generator with a sequence.您将生成器与序列混淆了。 A sequence is, by definition ,根据定义,序列是

An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence.通过__getitem__()特殊方法支持使用整数索引进行有效元素访问的可迭代对象,并定义了返回序列长度的__len__()方法。

A generator supports neither, and it's not a kind of mapping, either, so you can't pass one to pd.concat .生成器既不支持,也不是一种映射,因此您不能将一个传递给pd.concat

First of all since the generator expression in my code has SendType and ReturnType of None so Generator[DataFrame, None, None] is the correct type see docs .首先,因为我的代码中的生成器表达式的 SendType 和 ReturnType 为 None 所以Generator[DataFrame, None, None]是正确的类型,请参阅 文档 So as chepner has pointed out the problem lies in the expected type.所以正如chepner指出的那样,问题在于预期的类型。 Even though pandas.concat excepts generators data-science-types does not have it as possible input type for it.尽管pandas.concat除了生成器data-science-types没有将其作为可能的输入类型。 I would have considered that a bug but on their github page data-science-types they write我会认为这是一个错误,但在他们的github 页面data-science-types 上他们写了

Philosophy: [...] Often the actual APIs in the libraries is more permissive than the type signatures in our stubs;理念:[...] 库中的实际 API 通常比我们的存根中的类型签名更宽松; but this is (usually) a feature and not a bug.但这(通常)是一个功能而不是一个错误。

And I consider the problem solved.我认为问题已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM