[英]Python type hints with imported class methods
為了將大型 class 拆分為多個文件,此答案建議在class
級別使用import
命令來加載其定義可以移動到其他模塊的方法。 作為一個最小的例子,
class_def.py
:
class C:
from _methods import m
_methods.py
:
def m(self):
return "hello"
通常,大多數具有代碼完成功能的 IDE 會將在某些 class 中定義的函數識別為綁定方法,並且self
將自動被識別為具有定義該方法的 class 的類型。 不幸的是,在上述情況下,我沒有在 class 中定義m
。 僅看_methods.py
就無法判斷self
應該具有類型C
。
在m
的定義中,如果我插入以self.
,我的 IDE 無法建議m
或我可能在C
中實施的任何其他方法。
顯而易見的解決方案是添加類型提示:
from class_def import C
def m(self: C):
return "hello"
但是現在我們有一個循環導入: C
的定義導入_methods
,但_methods
導入C
。 如何在不引入循環導入的情況下創建類型提示?
我目前正在使用 Python 3.7,但我也對需要更高版本的解決方案感興趣。
修復循環導入,僅在類型檢查期間使用typing.TYPE_CHECKING
標志導入C
。
這使得C
的值在運行時未定義。 將其括在引號 ( "C"
) 中或導入__future__.annotations
:
_methods.py
變體 1:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from class_def import C
def m(self: "C"):
return "hello"
_methods.py
變體 2:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from class_def import C
def m(self: C):
return "hello"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.