简体   繁体   English

Mypy:用类类型注释变量

[英]Mypy: annotating a variable with a class type

I am having some trouble assigning the variables in a Python 3.6 class to a particular type--a Pathlib path. 我在将Python 3.6类中的变量分配给特定类型(Pathlib路径)时遇到了一些麻烦。 Following an example from link , I tried to create a TypeVar , but mypy is still throwing errors. 根据链接的示例,我尝试创建一个TypeVar ,但mypy仍然会抛出错误。 I want to make sure that the class variables initialized in the __init__.py only receive a particular type at compile time. 我想确保在__init__.py初始化的类变量仅在编译时接收特定类型。 So this is just a check to make sure I don't inadvertently set a string or something else to these class variables. 所以这只是一个检查,以确保我不会无意中为这些类变量设置字符串或其他东西。

Can anyone suggest the correct way to do this? 任何人都可以建议正确的方法吗?

Here is some simple code. 这是一些简单的代码。

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

The error that I am getting is: 我得到的错误是:

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

Neither Type, TypeVar nor NewType are correct to use here. Type,TypeVar和NewType都不正确。 What you simply want to do is use Path itself: 你只想做的就是使用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']

If you annotate your argsdict as being of type Dict[str, Path] , you can skip having to annotate your fields entirely: mypy will infer the correct type: 如果你将你的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']

Here's a brief explanation of what the various type constructs you were attempting to use/was suggested to you actually do: 以下是您尝试使用/建议实际执行的各种类型构造的简要说明:

  1. TypeVar is used when you are trying to create a generic data structure or function. 当您尝试创建通用数据结构或函数时,将使用TypeVar For example, take List[int] , which represents a list containing ints. 例如,使用List[int] ,它表示包含int的列表。 List[...] is an example of a generic data structure: it can be parameterized by any arbitrary type. List[...]是通用数据结构的一个示例:它可以通过任意类型进行参数化

    You use TypeVar as a way of adding "parameterizable holes" if you decide you want to create your own generic data structure. 如果您决定要创建自己的通用数据结构,可以使用TypeVar作为添加“可参数化孔”的方法。

    It's also possible to use TypeVars when writing generic functions. 编写泛型函数时也可以使用TypeVars For example, suppose you want to declare that you have some function that can accept a value of any type -- but that function is guaranteed to return a value of the exact same type. 例如,假设您要声明您有一些可以接受任何类型值的函数 - 但该函数保证返回完全相同类型的值。 You can express ideas like these using TypeVars . 您可以使用TypeVars表达这些TypeVars

  2. The Type[...] annotation is used to indicate that some expression must be the type of a type. Type[...]注释用于指示某个表达式必须是类型的类型。 For example, to declare that some variable must hold an int, we would write my_var: int = 4 . 例如,要声明某个变量必须包含int,我们将编写my_var: int = 4 But what if we want to write something like my_var = int ? 但是如果我们想写一些像my_var = int东西呢? What sort of type hint could we give that variable? 我们可以给那个变量什么类型的提示? In this case, we could do my_var: Type[int] = int . 在这种情况下,我们可以做my_var: Type[int] = int

  3. NewType basically lets you "pretend" that you're taking some type and making a subclass of it -- but without requiring you to actually subclass anything at runtime. NewType基本上允许你“假装”你正在使用某种类型并创建它的子类 - 但是不需要你在运行时实际上子类化任何东西。 If you're careful, you can take advantage of this feature to help catch bugs where you mix different "kinds" of strings or ints or whatever -- eg passing in a string representing HTML into a function expecting a string representing SQL. 如果您小心,您可以利用此功能来帮助捕获混合不同“种类”的字符串或整数或其他内容的错误 - 例如,将表示HTML的字符串传递到期望表示SQL的字符串的函数中。

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

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

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