0

我正在使用pytype(2019.10.17,到目前为止的最新版本)作为我的代码类型检查器来开发一个工具,它可以通过使用索引文件随机读取msgpack文件,该文件记录位置(msgpack文件中的偏移量) ) 每条消息(存储在 msgpack 中的值)。

在消息类型的多样性方面,我使用typing.TypeVar泛型类型来实现。pytype 使用 TypeVar 时遇到问题。

Name: pytype
Version: 2019.10.17
Summary: Python type inferencer
Home-page: https://google.github.io/pytype
Author: None
Author-email: None
License: UNKNOWN
Location: /home/gaoyunpeng/miniconda3/envs/restore/lib/python3.6/site-packages
Requires: ninja, typed-ast, six, importlab, pyyaml, attrs
Required-by:
Python 3.6.4 :: Anaconda, Inc.
from typing import TypeVar
T = TypeVar('T')

def f(x: T):
  print(x)

使用命令运行上述代码pytype main2.py

Computing dependencies
Analyzing 1 sources with 0 local dependencies
ninja: Entering directory `/home/gaoyunpeng/workspace/.pytype'
[1/1] check main2
FAILED: /home/gaoyunpeng/workspace/.pytype/pyi/main2.pyi
pytype-single --imports_info /home/gaoyunpeng/workspace/.pytype/imports/main2.imports --module-name main2 -V 3.6 -o /home/gaoyunpeng/workspace/.pytype/pyi/main2.pyi --analyze-annotated --nofail --quick /home/gaoyunp
eng/workspace/main2.py
File "/home/gaoyunpeng/workspace/main2.py", line 4, in <module>: Invalid type annotation 'T'  [invalid-annotation]
  Appears only once in the signature

For more details, see https://google.github.io/pytype/errors.html#invalid-annotation.
ninja: build stopped: subcommand failed.

如前所述https://google.github.io/pytype/errors.html#invalid-annotation,这种情况是无效注释。

为什么代码不能通过pytype检查?

4

1 回答 1

0

打印出来的错误信息解释了为什么这是一个类型错误。正如节目所说。引用错误消息的相关部分:

File "/home/gaoyunpeng/workspace/main2.py", line 4, in <module>: Invalid type annotation 'T'  [invalid-annotation]
  Appears only once in the signature

在给定的签​​名中只使用一次 TypeVar 是错误的,因为这样做毫无意义。在您的情况下,您不妨只使用类型签名def f(x: object) -> None。你想说f可以接受任何东西,Python 中的一切都是object.

只有当您想坚持两个或多个类型完全相同时,您才应该使用泛型类型。例如,如果你想定义一个“身份”函数,使用泛型类型是正确的:

def identity(x: T) -> T:
    return x

这将允许类型检查器推断identity("foo")identity(4)分别属于 str 和 int 类型——返回类型始终与参数类型相同。

请注意,“对于每个签名,您应该始终使用 TypeVar 两次或更多次”规则也适用于泛型类中的方法。当你这样做时:

class Foo(Generic[T]):
    def test(self, x: T) -> None: pass

...的签名test实际上是def test(self: Foo[T], x: T) -> None。所以我们也总是隐含地使用 TypeVar 两次。

于 2019-11-05T15:35:22.693 回答