如何实现装饰器来强制 Python 类型提示?

4

最近我一直在使用类型提示。在某些情况下,强制自动类型而不是针对每个类型提示变量的样板文件isinstance将非常有用。拥有一个能够实现这一点的装饰器将是无缝的,但我甚至不确定这在Python中是否可能。

如何实现一个强制类型提示的装饰器?例如,具有函数g的功能但使用h的语法。

def f(a:str, b:int) -> str:
    c = a * b
    return c

f("XXYYZZ", 3)
# 'XXYYZZXXYYZZXXYYZZ'
f(1, "3") # I understand why this works but was wondering if there is a way to seamlessly assert arguments types
# '3'

def g(a:str, b:int) -> str:
    assert isinstance(a, str)
    assert isinstance(b, int)

    c = a * b
    return c

g(1, "3") 
# ---------------------------------------------------------------------------
# AssertionError                            Traceback (most recent call last)
# <ipython-input-244-c13aa517b8e9> in <module>
#      15     return c
#      16 
# ---> 17 g(1, "3")

# <ipython-input-244-c13aa517b8e9> in g(a, b)
#       9 
#      10 def g(a:str, b:int) -> str:
# ---> 11     assert isinstance(a, str)
#      12     assert isinstance(b, int)
#      13 

# AssertionError: 

@assert_types(inputs=True, outputs=False)
def h(a:str, b:int) -> str:
    c = a * b
    return c

1
你可以实现这个功能,不过已经有一些项目(例如 pydantic)已经完成了这项工作。但是请考虑使用静态类型检查器(例如 mypy),而不是运行时类型检查。 - juanpa.arrivillaga
1个回答

2
你可以尝试使用这个装饰器,但是像@juanpa.arrivillaga说的那样,最好使用mypy。
def asset_types(func):
    def wrapper(a,b, *args):
       assert isinstance(a, str)
       assert isinstance(b, int)
       func(a,b)
    return wrapper

@asset_types
def h(a:str, b:int) -> str:
    c = a * b
    return c 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接