0

我有以下内容:

在 myfile.py 中:

from file1 import REQ
@has_request_variable
def fun(request, REQ(validator=check_int))
   /* body */

在文件 1.py

class REQ(object):
    def __init__(self, validator=None):
        self.validator = validator

def has_request_variables(view_func):
       /* body */
       # Below I am calling the validator function to check
       error = param.validator(var_name, val)

现在我想使用 mypy 注释有趣的函数,我已经按照以下方式完成了它并且它工作但它并不理想,因为在乐趣中我知道消息是 int 类型所以我们应该用类似 int 的东西来注释参数...如何使用 mypy 实现它。

from file1 import REQ
@has_request_variable
def fun(request, message=REQ(validator=check_int))
    # type(Any, REQ) -> Any
    msg = message # type: int
   /* body */
4

1 回答 1

0

首先,mypy 与类型注解没有直接关系。您可以在不注释代码的情况下使用 mypy,因为 mypy 是一个使用类型推断(和类型注释,如果存在)来对代码进行类型检查的程序。此外,您可以在没有 mypy 的情况下使用类型注释 - 用于许多有用的目的,例如文档、代码可读性等。

其次,mypy 是一个静态类型检查器。在检查类型时,您的程序没有运行,因此尝试使用 mypy 进行运行时类型检查是没有意义的(这有点像我在问题代码中看到的)。

因此,如果您想要静态类型检查,请使用annotations。但是,如果你想在运行时进行类型检查,你可以使用assertions。或者你可以同时使用它们...

类型注释(用于使用 mypy 进行静态类型检查):

根据PEP,类型注释可以让您从以下代码中走出来:

def print_many(what, how_many=10):
    long_what = how_many * what
    print(long_what)

为此,您有函数参数、返回类型以及任何带注释的局部变量:

def print_many(what: str, how_many: int=10) -> None:
    long_what = how_many * what # type: str
    print(long_what)

对于您的特定用例,如果您知道这message是 type int,那么:def fun(request, message: int)将完成这项工作。

您可以只在带注释的代码上运行 mypy 并获得结果,但您的代码只会进行类型检查,不会被执行。所以参数的默认值,例如REQ(validator=check_int)被 mypy 完全忽略。

请记住,即使 PEP 0484 和typing模块是 Python 3.5 的官方部分,mypy 也是一个单独的项目,它在许多情况下已经运行良好,但仍在开发中。

运行时类型检查的断言:

def fun(request, message: int):
    assert isinstance(message, int)
    # function body

mypy 会忽略此类断言,但会在您的函数执行时对其进行检查。

于 2016-05-07T16:24:51.477 回答