代码之家  ›  专栏  ›  技术社区  ›  Evandro Pomatti

从函数返回“any”时,在Python中声明或“强制转换”为实际类型

  •  0
  • Evandro Pomatti  · 技术社区  · 3 年前

    我正在使用的函数返回 any 作为类型,我在代码中找不到建议。

    我该如何制作我的 core_client 变量应为实际类型 <CoreClient> <azure.devops.released.core.core_client.CoreClient> ?

    我试着调查 any 规范,但在那里找不到它的指南。

    有什么选择可以让它发挥作用?

    这是我调用的SDK函数:

    def get_core_client(self):
        """get_core_client.
        Gets the 5.1 version of the CoreClient
        :rtype: :class:`<CoreClient> <azure.devops.released.core.core_client.CoreClient>`
        """
        return self._connection.get_client('azure.devops.released.core.core_client.CoreClient')
    

    我无法得到任何建议,似乎 任何 返回类型是原因:

    core_client = connection.clients.get_core_client()
    core_client.*** # no suggestions here
    

    SDK来自 https://pypi.org/project/azure-devops/

    enter image description here

    1 回复  |  直到 3 年前
        1
  •  3
  •   Joran Beasley    3 年前

    core_client:CoreClient = connection.clients.get_core_client()

    那么你应该得到提示。。。。(取决于您的IDE)

    通常为ide 理解是事实

    如果你添加 assert isinstance(core_client,CoreClient) IDE的意愿 ( 一些 将识别一个块 if isinstance(core_client,CoreClient): )也可以接受这一点,但通常在生产代码中使用断言不是一个好主意(但你可以……)

    请记住,粗略指定类型不会指定任何类型的可执行合同( core_client:CoreClient = ... )实际上只是为了语法辅助(和autodoc的东西……)