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

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

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

简单的例子:

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()

最佳答案

可能是类型检查器问题。解决方案如下。使用 mypy 没问题,但 pycharmpyre-check 正在提示。

from typing import *

def example_decorator(
    fn: Callable[[List[str]], List[str]]
) -> Callable[[List[str]], str]:
    def wrapper(data: List[str]) -> str:
        res = fn(data)
        return ', '.join(res)

    return wrapper


@example_decorator
def func(data: List[str]) -> List[str]:  
    data.append('XYZ')
    return data


def test() -> str:
    result = func(['ABC', 'EFG'])
    print(type(result))  # <class 'str'>
    return result


test()

关于python - 装饰器更改返回类型时键入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409421/

相关文章:

python - 如何使用 Python 查询作为 Mongodb 中列表字段的列表中命中元素的计数?

python - 如何在mypy中使用reveal_type

python - 尝试注销 django 时出现运行时错误

python-3.x - 调试器操作正在进行中

python - 计算到达目标的步行点数

python-3.x - 在快速 api 中全局捕获 `Exception`

Python 类型提示 : How do I enforce that project wide?

python - python 类中的方法可以用子类定义的类型进行注释吗?

python - 如何覆盖 sys.stdin 以复制输入流

python - 如何用条件元素组成列表