装饰器更改返回类型时的键入功能 [英] Typing function when decorator change return type

查看:46
本文介绍了装饰器更改返回类型时的键入功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to correctly write types for the function whose return type is modified by decorator ?

简单例子:

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 有问题.

May be a typechecker problem. Solution below. With mypy its ok but pycharm and pyre-check is complaining.

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

这篇关于装饰器更改返回类型时的键入功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆