Reputation: 30717
I've been using type hinting as of late. In some cases, it would be useful to force the type automatically instead of the boilerplate of isinstance
for every type hinted variable. It would be seamless to have a decorator that could do this but I'm not even sure if this is possible in Python.
How would one implement a decorator that forces the type hinting? For example, having the capabilities of function g
but the syntax of 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
Upvotes: 4
Views: 773
Reputation: 1486
You can try this decorator, however, like @juanpa.arrivillaga said, you are better using 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
Upvotes: 2