简体   繁体   English

Google Colab 在多大程度上支持 Python 打字?

[英]To what extent does Google Colab support Python typing?

I've entered code that had these lines.我输入了包含这些行的代码。

from typing import Dict, List, Set, Tuple

def pairs_sum_to_k(a_set: Set[int], k: int) -> List[Tuple[int, int]]:
    ...

The code compiled and ran.代码编译并运行。 That's good.那挺好的。 It's also good that when I attempted to import something that wasn't in typing Colab generated an error message.这也很好,当我尝试导入不是在 Colab 中typing的内容时,生成了一条错误消息。

What's not good is that when the type hints were inconsistent with the program, , eg, change the return type to a simple int , Colab didn't complain.不好的是,当类型提示与程序不一致时,例如,将返回类型更改为简单的int ,Colab 没有抱怨。 This suggests that Colab can deal with type hint syntax, but that it doesn't do anything at all with the type declarations.这表明 Colab 可以处理类型提示语法,但它对类型声明根本不做任何事情。 Is that the case?是这样吗? What kind of typing support, if any, should I expect from Colab?我应该期望 Colab 提供什么样的打字支持(如果有)?

Thanks.谢谢。

Type annotations in Python are just decoration – Python does not do any type validation natively. Python 中的类型注释只是装饰——Python 本身不进行任何类型验证。 From the Python docs :来自Python 文档

Note: The Python runtime does not enforce function and variable type annotations.注意: Python 运行时不强制执行 function 和变量类型注释。 They can be used by third party tools such as type checkers, IDEs, linters, etc.它们可以被第三方工具使用,例如类型检查器、IDE、linters 等。

If you want to validate your types, you need to use a tool like mypy , which is designed to do this.如果你想验证你的类型,你需要使用像mypy这样的工具,它被设计用来做这个。

I'm not aware of any built-in type checking functionality in Colab, but it's relatively straightforward to define yourself.我不知道 Colab 中有任何内置的类型检查功能,但定义自己相对简单。 For example, you could create a Jupyter cell magic that performs typechecks on the cell contents using mypy:例如,您可以创建一个 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)

Then you can use it like this:然后你可以像这样使用它:

%%mypy

def foo(x: int) -> int:
  return 2 * x

foo('a')

Upon execution, this is the output:执行后,这是 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.

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