如何实现装饰器强制 Python 类型提示?
How to implement decorator to force Python type hinting?
最近我一直在使用类型提示。在某些情况下,为每个类型提示变量自动强制类型而不是 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
你可以试试这个装饰器,但是,就像@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
最近我一直在使用类型提示。在某些情况下,为每个类型提示变量自动强制类型而不是 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
你可以试试这个装饰器,但是,就像@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