3

我最近一直在使用类型提示。isinstance在某些情况下,自动强制类型而不是每个类型提示变量的样板文件会很有用。拥有一个可以做到这一点的装饰器是无缝的,但我什至不确定这在 Python 中是否可行。

如何实现一个强制类型提示的装饰器?例如,具有 function 的功能,g但具有 function 的语法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
4

1 回答 1

1

你可以试试这个装饰器,但是,就像@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 
于 2021-04-12T19:20:54.537 回答