簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM