[英]To what extent does Google Colab support Python typing?
我输入了包含这些行的代码。
from typing import Dict, List, Set, Tuple
def pairs_sum_to_k(a_set: Set[int], k: int) -> List[Tuple[int, int]]:
...
代码编译并运行。 那挺好的。 这也很好,当我尝试导入不是在 Colab 中typing
的内容时,生成了一条错误消息。
不好的是,当类型提示与程序不一致时,例如,将返回类型更改为简单的int
,Colab 没有抱怨。 这表明 Colab 可以处理类型提示语法,但它对类型声明根本不做任何事情。 是这样吗? 我应该期望 Colab 提供什么样的打字支持(如果有)?
谢谢。
Python 中的类型注释只是装饰——Python 本身不进行任何类型验证。 来自Python 文档:
注意: Python 运行时不强制执行 function 和变量类型注释。 它们可以被第三方工具使用,例如类型检查器、IDE、linters 等。
如果你想验证你的类型,你需要使用像mypy这样的工具,它被设计用来做这个。
我不知道 Colab 中有任何内置的类型检查功能,但定义自己相对简单。 例如,您可以创建一个 Jupyter 单元格魔法,使用 mypy 对单元格内容执行类型检查:
# Simple mypy cell magic for Colab
!pip install mypy
from IPython.core.magic import register_cell_magic
from IPython import get_ipython
from mypy import api
@register_cell_magic
def mypy(line, cell):
for output in api.run(['-c', '\n' + cell] + line.split()):
if output and not output.startswith('Success'):
raise TypeError(output)
get_ipython().run_cell(cell)
然后你可以像这样使用它:
%%mypy
def foo(x: int) -> int:
return 2 * x
foo('a')
执行后,这是 output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-21dcff84b262> in <module>()
----> 1 get_ipython().run_cell_magic('mypy', '', "\ndef foo(x: int) -> int:\n return 2 * x\n\nfoo('a')")
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2115 magic_arg_s = self.var_expand(line, stack_depth)
2116 with self.builtin_trap:
-> 2117 result = fn(magic_arg_s, cell)
2118 return result
2119
<ipython-input-5-d2e45a31f6bb> in mypy(line, cell)
8 for output in api.run(['-c', '\n' + cell] + line.split()):
9 if output:
---> 10 raise TypeError(output)
11 get_ipython().run_cell(cell)
TypeError: <string>:6: error: Argument 1 to "foo" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.