相关疑难解决方法(0)

装饰器更改返回类型时键入函数

如何正确编写返回类型被装饰器修改的函数的类型?

简单的例子:

def example_decorator(fn):
    def wrapper(data):
        res = fn(data)
        return ', '.join(res)

    return wrapper


@example_decorator
def func(data: list):  # -> ???? str ? list ?
    new_data = data
    new_data.append('XYZ')
    return new_data


# When we type func -> list

def test() -> str:
    result = func(['ABC', 'EFG'])
    print(type(result))  # <class 'str'>
    return result  # Incompatible return type [7]: Expected str but got list.


test()
Run Code Online (Sandbox Code Playgroud)

python python-3.x mypy python-typing pyre-check

6
推荐指数
1
解决办法
2805
查看次数

标签 统计

mypy ×1

pyre-check ×1

python ×1

python-3.x ×1

python-typing ×1