Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement decorator to force Python type hinting?

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
like image 667
O.rka Avatar asked Oct 28 '25 17:10

O.rka


1 Answers

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 
like image 160
Ade_1 Avatar answered Oct 31 '25 13:10

Ade_1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!