最近我一直在使用类型提示。在某些情况下,强制自动类型而不是针对每个类型提示变量的样板文件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
pydantic
)已经完成了这项工作。但是请考虑使用静态类型检查器(例如mypy
),而不是运行时类型检查。 - juanpa.arrivillaga