代码之家  ›  专栏  ›  技术社区  ›  krishnab

Mypy:用类类型注释变量

  •  1
  • krishnab  · 技术社区  · 7 年前

    link ,我试图创建 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 回复  |  直到 7 年前
        1
  •  5
  •   Michael0x2a    7 年前

    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]

    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']
    

    以下是您试图使用/建议您实际执行的各种类型构造的简要说明:

    1. TypeVar 在尝试创建通用数据结构或函数时使用。例如,以 List[int] List[...] 是通用数据结构的一个示例:它可以是 参数化

      你用 作为添加“可参数化孔”的一种方法,如果您决定创建自己的通用数据结构。

      也可以使用 TypeVars 在编写泛型函数时。例如,假设您想声明您有一个函数可以接受任何类型的值,但是该函数是 放心 返回完全相同类型的值。你可以用 类型变量

    2. Type[...] 注释用于指示某些表达式必须是类型的类型。例如,要声明某个变量必须包含int,我们将编写 my_var: int = 4 my_var = int ? 我们能给那个变量什么类型的提示?在这种情况下,我们可以 my_var: Type[int] = int .

    3. NewType 基本上可以让您“假装”要获取某个类型并生成其子类,但不要求您在运行时实际为任何类型创建子类。如果你很小心,你可以利用这个特性来帮助捕捉你混合不同“种类”的字符串或整数或其他东西的错误——例如,把一个代表HTML的字符串传递到一个期望代表SQL的字符串的函数中。

        2
  •  2
  •   Daniel Severo    7 年前

    替换 TypeVar NewType 并移除 Type[]