Python 类型:如何将变量类型提示为绑定方法?

pep*_*uan 10 type-hinting python-3.6

所以我有一个函数(我们称之为fun1),它接受一个函数作为参数。但在内部fun1,我需要访问参数的__self__,该参数仅当函数是绑定方法时才存在。

函数本身必须接受两个str参数并返回一个bool

换句话说,像这样:

MyFuncType = Callable[[str, str], bool]

# fun1 is an unbound function
def fun1(func: MyFuncType):
    ...
    o = func.__self__
    ...
    # Some logic on the "o" object, such as logging the object's class,
    # doing some inspection, etc.
    ...
Run Code Online (Sandbox Code Playgroud)

如果我MyFuncType像上面那样使用,PyCharm 会抱怨 that __self__is not a attribute of func.

那么,我应该用什么类型提示func进行注释,以便 PyCharm(可能还​​有 mypy)不会对该行提出抗议?

(顺便说一句,我正在使用Python 3.6 )

pep*_*uan 3

好吧,经过一些实验,我解决了这个问题:

class BoundFunc:
    __self__: object

MyFuncType = Callable[[str, str], bool]
MyBoundFuncType = Union[MyFuncType, BoundFunc]

def fun1(func: MyBoundFuncType):
    ...
    o = func.__self__
    ...
Run Code Online (Sandbox Code Playgroud)

如果我将未绑定的函数传递给 ,这不会警告我fun1,但至少当我尝试访问该__self__属性时它会抑制 PyCharm 的警告。

我认为一个正确的文档字符串fun1明确表示func必须是一个绑定方法对于成年人来说应该足够了......