如何为装饰为更改函数返回值的函数键入提示返回值?

PMe*_*nde 5 python pycharm python-3.x

我正在编写一个Python包,该包使用装饰器删除样板代码,同时对函数进行自省以获取默认的函数名。类似于以下内容:

def make_real_instance(func: Optional[Callable] = None,
                       *, func_name: Optional[str] = None):
    def make_wrapper(in_func):
        @functools.wraps(in_func)
        def wrapper(*args, **kwargs):
            nonlocal func_name
            # Use func_name if provided
            func_name = func_name or in_func.__name__
            # Construct params for new object from function and its inputs
            stuff = in_func(*args, **kwargs)
            # Process stuff commonly
            new_object = ObjectConstructor(processed_stuff, func_name)
            return new_object
        return wrapper

    if func:
        return make_wrapper(func)
    return make_wrapper
Run Code Online (Sandbox Code Playgroud)

现在,我有这样的课程:

class ObjectConstructor:
    def __init__(self, ...):
        #do stuff

    @make_real_instance
    def add_foo(self, foo_length: float):
        stuff = ... # process the input for this method
        return stuff
Run Code Online (Sandbox Code Playgroud)

@make_real_instance装饰引起的调用add_foo实例的方法ObjectConstructor返回一个新的实例。但是,未修饰方法的实际返回类型是元组。

我想做的是注释该方法,以键入hint return作为的实例ObjectConstructor。即行:

        def add_foo(self, foo_length: float):
Run Code Online (Sandbox Code Playgroud)

将成为(annotations已从导入__future__):

        def add_foo(self, foo_length: float): -> ObjectConstructor
Run Code Online (Sandbox Code Playgroud)

但是,我的IDE(PyCharm,尽管在这种情况下我不一定认为是实质性的)抱怨(很公平,我想)此方法的输出与提示的返回类型不匹配。

最后,我的问题是:有没有一种方法可以正确地提示使用修改器修饰输出的函数调用的返回类型?还是我唯一的方法是将装饰器更改为我在装饰的每个函数中调用的函数,并且func_name每次都显式传递参数?我的意思是这样的:

def make_obj_from_stuff(stuff, func_name) -> ObjectConstructor:
    # process stuff commonly
    new_object = new_object = ObjectConstructor(processed_stuff, func_name)
    return new_object

class ObjectConstructor:
    def __init__(self, ...):
        #do stuff

    def add_foo(self, foo_length: float) -> ObjectConstructor:
        stuff = ... # process the input
        new_obj = make_obj_from_stuff(stuff, "add_foo")
        return new_obj
Run Code Online (Sandbox Code Playgroud)

如果我想维护自己创建的装饰器接口,是否只需要接受我不会抱怨IDE便不能正确键入提示的想法?