Mypy:用 class 类型注释变量

Mypy: annotating a variable with a class type

我在将 Python 3.6 class 中的变量分配给特定类型 -- Pathlib 路径时遇到了一些问题。按照 link 中的示例,我尝试创建一个 TypeVar,但 mypy 仍然抛出错误。我想确保在 __init__.py 中初始化的 class 变量仅在编译时接收特定类型。所以这只是一个检查,以确保我不会无意中为这些 class 变量设置字符串或其他内容。

任何人都可以建议正确的方法吗?

这是一些简单的代码。

import pathlib
from typing import Union, Dict, TypeVar, Type

Pathtype = TypeVar('Pathtype', bound=pathlib.Path)

class Request:

    def __init__(self, argsdict):

        self._dir_file1: Type[Pathtype] = argsdict['dir_file1']
        self._dir_file2: Type[Pathtype] = argsdict['dir_file2']

我得到的错误是:

Request.py:13: error: Invalid type "Request.Pathtype"
Request.py:14: error: Invalid type "Request.Pathtype"

TypeVar 替换为 NewType 并删除 Type[] 修饰符。

在这里使用 Type、TypeVar 和 NewType 都不正确。您只想做的是使用 Path 本身:

from pathlib import Path

class Request:
    def __init__(self, argsdict):
        self._dir_file1: Path = argsdict['dir_file1']
        self._dir_file2: Path = argsdict['dir_file2']

如果您将 argsdict 注释为 Dict[str, Path] 类型,您可以跳过必须完全注释您的字段:mypy 将推断出正确的类型:

from typing import Dict
from pathlib import Path

class Request:
    def __init__(self, argsdict: Dict[str, Path]):
        self._dir_file1 = argsdict['dir_file1']
        self._dir_file2 = argsdict['dir_file2']

这里简要解释了您尝试 use/was 建议您实际执行的各种类型构造:

  1. TypeVar 在您尝试创建通用数据结构或函数时使用。例如,以 List[int] 为例,它表示包含整数的列表。 List[...] 是通用数据结构的一个例子:它可以被任意类型参数化

    如果您决定要创建自己的通用数据结构,则可以使用 TypeVar 作为添加 "parameterizable holes" 的方式。

    也可以在编写通用函数时使用 TypeVars。例如,假设您想声明您有一些函数可以接受任何类型的值——但该函数是 保证 到 return 完全相同的值类型。您可以使用 TypeVars.

  2. 来表达这些想法
  3. Type[...]注解用来表示某个表达式必须是某个类型的类型。例如,要声明某个变量必须包含一个 int,我们可以写成 my_var: int = 4。但是如果我们想写类似 my_var = int 的东西怎么办?我们可以给那个变量什么样的类型提示?在这种情况下,我们可以做 my_var: Type[int] = int.

  4. NewType 基本上让您 "pretend" 您正在获取某种类型并创建它的子类——但不需要您在运行时实际子类化任何东西。如果您小心的话,您可以利用此功能来帮助捕获混合不同 "kinds" 字符串或整数或其他任何内容的错误——例如将表示 HTML 的字符串传递给需要表示 SQL.

  5. 的字符串的函数