如何实现decorator来强制Python类型暗示?
我最近一直在使用打字暗示。在某些情况下,对于每个类型暗示的变量,自动强制输入类型而不是使用如何实现decorator来强制Python类型暗示?,python,types,decorator,assert,type-hinting,Python,Types,Decorator,Assert,Type Hinting,我最近一直在使用打字暗示。在某些情况下,对于每个类型暗示的变量,自动强制输入类型而不是使用isinstance的样板文件会很有用。如果有一个装饰器可以做到这一点,那将是天衣无缝的,但我甚至不确定这在Python中是否可行 如何实现强制类型暗示的装饰器?例如,具有函数g的功能,但函数h的语法 def f(a:str, b:int) -> str: c = a * b return c f("XXYYZZ", 3) # 'XXYYZZXXYYZZXXYYZ
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
def(a:str,b:int)->str:
c=a*b
返回c
f(“xxyyz”,3)
#“xxyzzxxyzzxxyzz”
f(1,“3”)#我理解为什么这样做有效,但想知道是否有一种方法可以无缝地断言参数类型
# '3'
def g(a:str,b:int)->str:
断言isinstance(a,str)
断言isinstance(b,int)
c=a*b
返回c
g(1,“3”)
# ---------------------------------------------------------------------------
#AssertionError回溯(上次最近的调用)
#在
#15返回c
# 16
#--->17克(1,“3”)
#在g(a,b)中
# 9
#10 def g(a:str,b:int)->str:
#-->11断言为实例(a,str)
#12断言isinstance(b,int)
# 13
#断言者错误:
@断言类型(输入=真,输出=假)
def h(a:str,b:int)->str:
c=a*b
返回c
你可以试试这个装饰器,但是,就像@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
您可以实现这一点,尽管有些项目已经完成了不必要的工作(例如,
pydantic
)。但是,考虑运行时类型检查,只需使用静态类型检查器,例如“代码> MyPy < /代码>