[英]python 3: type inferencing with mypy?
在python 3中給出以下代碼段
def foo() -> List[X]: pass
class X:
def bar(self) -> MYTYPE: pass
對於以下表達式:
[x.bar() for x in foo()]
我可以利用mypy
包正確解析上面表達式的AST並猜測結果的類型是List[MYTYPE]
嗎?
如果不能,我的最佳選擇是什么? 有什么想法/套餐可以推薦嗎?
是的,它會推斷出來。 這是一個演示:
from typing import List
class MyType:
pass
class X:
def bar(self) -> MyType: pass
def foo() -> List[X]: pass # note the square brackets
bars = [x.bar() for x in foo()]
reveal_type(bars)
然后,當您在終端中運行mypy script.py
,您會看到一條消息:
Revealed type is 'builtins.list[script.MyType*]'
有關reveal_type
文檔在此處 。
順便說一下,您的代碼有一個小問題,應該是List[X]
而不是List(X)
。
PyCharm也會識別類型。 bars.
將為列表方法和bars[0].
提供自動完成選項bars[0].
將為MyType
提供選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.