簡體   English   中英

Python 將返回類型注釋為賦予函數的類型

[英]Python annotate return type as the type given to function

我正在給一個類型的功能。 該函數為我實例化類型。 該類型實現BaseCustomObject但它是許多可能的類型之一。

def factory(object_to_create:[T], parameter:int=1) -> [T]:
    constructor_parameter = calculation(parameter)
    return object_to_create(constructor_parameter)

my_custom_object_instance = factory(MyCustomObject)

我如何注釋factory以便很明顯它返回我發送的任何類型,而不僅僅是BaseCustomObject 我不喜歡使用聯合類型,而是讓注釋/檢查/ide 准確了解我要返回的特定類型。

使用 TypeVar 泛型類型。 [T] 表示 T 的列表,而不是 T,所以不要這樣做。

如果 object_to_create 是一個函數,請執行此操作。

# Use bound to limit the type to a specific ancestor.
T = TypeVar("T", bound="BaseCustomObject") 

# Callable[..., T] is the type of a function 
# that takes in whatever argument and returns an instance of T.

def my_func(
  object_creator: Callable[..., T], 
  params: Optional[int] = 1
) -> T:
  return object_creator(params) # Will return a T.

如果 object_to_create 是一個class而不是一個函數,您可以使用Type[T] ,它是實際的類而不是類實例。

# Use bound to limit the type to a specific ancestor.
T = TypeVar("T", bound="BaseCustomObject") 

def my_func(
  object_to_create: Type[T], 
  params: Optional[int] = 1
) -> T:
  return object_to_create(params) # Will return an instance of object_to_create.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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