繁体   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