Google Colab 在多大程度上支持 Python 类型?

Rus*_*ott 5 python google-colaboratory python-typing

我已经输入了包含这些行的代码。

from typing import Dict, List, Set, Tuple

def pairs_sum_to_k(a_set: Set[int], k: int) -> List[Tuple[int, int]]:
    ...
Run Code Online (Sandbox Code Playgroud)

代码编译并运行。那挺好的。当我尝试导入typingColab中没有的内容时,生成了一条错误消息,这也很好。

不好的是,当类型提示与程序不一致时,例如,将返回类型更改为 simple int,Colab 没有抱怨。这表明 Colab 可以处理类型提示语法,但它对类型声明根本不做任何事情。是这样吗?我应该期待 Colab 提供什么样的打字支持(如果有)?

谢谢。

jak*_*vdp 7

Python 中的类型注释只是装饰 \xe2\x80\x93 Python 本身不进行任何类型验证。来自Python文档

\n
\n

注意: Python 运行时不强制执行函数和变量类型注释。它们可以被第三方工具使用,例如类型检查器、IDE、linter 等。

\n
\n

如果您想验证您的类型,您需要使用像mypy这样的工具,它就是专门用于执行此操作的。

\n

我不知道 Colab 中有任何内置类型检查功能,但您自己定义相对简单。例如,您可以创建一个 Jupyter cell magic,使用 mypy 对单元格内容执行类型检查:

\n
# Simple mypy cell magic for Colab\n!pip install mypy\nfrom IPython.core.magic import register_cell_magic\nfrom IPython import get_ipython\nfrom mypy import api\n\n@register_cell_magic\ndef mypy(line, cell):\n  for output in api.run([\'-c\', \'\\n\' + cell] + line.split()):\n    if output and not output.startswith(\'Success\'):\n      raise TypeError(output)\n  get_ipython().run_cell(cell)\n
Run Code Online (Sandbox Code Playgroud)\n

然后你可以像这样使用它:

\n
%%mypy\n\ndef foo(x: int) -> int:\n  return 2 * x\n\nfoo(\'a\')\n
Run Code Online (Sandbox Code Playgroud)\n

执行后,输出如下:

\n
---------------------------------------------------------------------------\nTypeError                                 Traceback (most recent call last)\n<ipython-input-6-21dcff84b262> in <module>()\n----> 1 get_ipython().run_cell_magic(\'mypy\', \'\', "\\ndef foo(x: int) -> int:\\n  return 2 * x\\n\\nfoo(\'a\')")\n\n/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)\n   2115             magic_arg_s = self.var_expand(line, stack_depth)\n   2116             with self.builtin_trap:\n-> 2117                 result = fn(magic_arg_s, cell)\n   2118             return result\n   2119 \n\n<ipython-input-5-d2e45a31f6bb> in mypy(line, cell)\n      8   for output in api.run([\'-c\', \'\\n\' + cell] + line.split()):\n      9     if output:\n---> 10       raise TypeError(output)\n     11   get_ipython().run_cell(cell)\n\nTypeError: <string>:6: error: Argument 1 to "foo" has incompatible type "str"; expected "int"\nFound 1 error in 1 file (checked 1 source file)\n
Run Code Online (Sandbox Code Playgroud)\n