Mypy:用类类型注释变量

时间:2019-03-12 01:53:43

标签: python-3.x mypy

在将Python 3.6类中的变量分配给特定类型(Pathlib路径)时遇到一些麻烦。根据{{​​3}}的示例,我尝试创建一个TypeVar,但是mypy仍然会引发错误。我想确保在__init__.py中初始化的类变量在编译时仅接收特定类型。因此,这只是一项检查,以确保我不会无意中为这些类变量设置字符串或其他内容。

有人可以建议这样做的正确方法吗?

这是一些简单的代码。

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"

1 个答案:

答案 0 :(得分:1)

TypeVar替换为NewType,然后删除Type[]修饰符。