簡體   English   中英

Python 類型提示(用於返回類型)不適用於類和子類?

[英]Python type hinting (for return type) not working for classes vs subclasses?

編碼:

所以我有如下超級簡單的代碼文件:

首先,我的架構定義文件: schema.py

from pydantic import BaseModel


class BaseSchema(BaseModel):

    user_type: UserTypeEnum
    configuration_type: ConfigurationTypeEnum


class UserDataSchema(BaseSchema):

    user_type: UserTypeEnum.NORMAL
    configuration_type: ConfigurationTypeEnum.NORMAL

    user_name: str
    user_age: int

其次,我有一個類定義文件,比如class_file.py

class AnotherServiceClass(BaseClient):

    @property
    def client_name(self):
        return 'another_service_class'

    def get_call(self, schema_identifier_param: str) -> BaseSchema:
        url = 'some/url/constructed'
        return self.get(url)

然后我有一個調用上述類函數的文件: caller_function.py

def get_data_from_another_service(
    user_name: str,
    schema_identifier_param: str
) -> UserDataSchema:
    another_service_instance = AnotherServiceClass(
        user_name=user_name
    )
    return another_service_instance.get_call(schema_identifier_param)

問題:

這里, class_file.py中的AnotherServiceClass.get_call函數是一個通用函數,它可以返回任何類型的模式,它是BaseSchema的子模式; 因此-> BaseSchema:

caller_function.py文件中的get_data_from_another_service函數知道它應該始終獲取UserDataSchema 這是因為schema_identifier_param參數中傳遞的特定值。

問題是,我仍然在get_data_from_another_service函數中遇到類型提示錯誤; AnotherServiceClass.get_call返回BaseSchema ,但我隨后返回UserDataSchema

由於UserDataSchema繼承BaseSchema ,它不應該是有效的返回類型嗎?

我還嘗試將AnotherServiceClass.get_call的返回類型定義為:
get_call(self, schema_identifier_param: str) -> Type[BaseSchema]:
但這無濟於事。

我究竟做錯了什么?

並且 caller_function.py 文件中的 get_data_from_another_service 函數知道它應該始終獲取 UserDataSchema。 這是因為 schema_identifier_param 參數中傳遞的特定值。

這就是它出錯的地方。 Python 不知道“在 schema_identifier_param 中傳遞的特定值”會導致始終返回 UserDataSchema 的約定。 而且您不能在類型提示系統中輕松解釋這一點。 所以Python所說的大致是“我不明白為什么get_data_from_another_service會返回UserDataSchema”。 而 Python 在這方面是絕對正確的。

(此外,您的代碼也不以任何方式保證這一點。您返回的東西是由某個 url 返回的,因此您必須依靠遠程服務器行為使其始終返回 UserDataSchema。這是非常脆弱的。)

暫無
暫無

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

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