Strongtyping package

The package can be installed via `pip install -i https://test.pypi.org/simple/ strongtyping`

The problem:
def multipler(a: int, b: int):
    return a * b


product = multipler(3, 4)
# >>> 12

# Some IDE's will/can highlight that one of the parameter doesn't match
# but you can run it
product_2 = multipler('Hello', 'World')
# >>> TypeError

When we receiver an Exception then we are 'safe' and know what to do but sometimes you will not run into an Exception

product_3 = multipler('Hello', 4)
# >>> 'HelloHelloHelloHello'

The result isn't really what we expect.
Now we can say that we will check the types in the function body to prevent this.

def multipler(a: int, b: int):
if isinstance(a, int) and isinstance(b, int):
    return a * b
...

But when your function needs a lot of different parameters with different types you have to create a lot of noising code.

My solution:>

I created a decorator called **@match_typing** which will check at runtime if the parameters you used when calling this function are from the same type as you wanted. Here are some examples from my tests

@match_typing
def func_a(a: str, b: int, c: list):
    ...

result_1 = func_a('1', 2, [i for i in range(5)])
# >>> True

result_2 = func_a(1, 2, [i for i in range(5)])
# >>> will raise a TypeMismatch Exception

At the current state it will work with

  • builtin types like: str, int, tuple etc
  • from typing: List, Tuple, Union also nested ( Tuple[Union[str, int], Union[list, tuple]] )
  • with string types representation like
    class A:
        @match_typing
        def func_a(self, a: 'A'):
        


Link: strongtyping-pypi

08 Jun. 20
Zurück

© 2017 - 2020 FtC-Webdev