【问题标题】:What is the right Python annotation for imported method as variable?导入方法作为变量的正确 Python 注释是什么?
【发布时间】:2023-01-20 23:44:09
【问题描述】:

我正在寻找可用于注释导入的实例方法的 Method 类型,因为 Callable[[Self, ...], ...] 不起作用。

例子:

mod_method.py

from __future__ import annotations

import typing

if typing.TYPE_CHECKING:
    from class import Object


def meth_method(self: Object, val: int) -> float:
    return val + 10.5

类.py

from mod_method import meth_method


class Object:
    method: Method[[int], float] = meth_method

【问题讨论】:

    标签: python typing


    【解决方案1】:

    meth_method 是一个普通函数。您所想的意义上的实例方法只是一个函数值类属性。多亏了 descriptor protocol,当您通过类的实例访问属性时,您会获得一个方法(类型为 types.MethodType)。

    因此,正确的类型提示是types.FunctionType。 (不只是Callable,因为它是生成绑定方法的types.FunctionType.__get__。)

    class Object:
        method: types.FunctionType = meth_method
    

    FunctionType 不像 Callable 那样通用,所以不幸的是你不能更具体,比如 types.FunctionType[[Object, int], float]


    顺便说一句,我建议不要将类定义与模块外部定义的函数拼凑在一起。您可能有一个要解决的 XY Problem

    【讨论】:

    • 谢谢您的回答。所以没有办法正确注解types.FunctionType?
    • 不具体,但我很好奇您认为有必要的用例。
    • 好的,我要更新问题。
    【解决方案2】:

    作为变量导入方法的正确 Python 注释是:

    @typing.overload
    def varName(...) -> returnType:
        ...
    

    【讨论】:

    • 我投反对票,因为这个答案毫无意义 - 超载在这里做什么?
    猜你喜欢
    • 2012-11-30
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2019-09-04
    • 2016-01-11
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多