You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How to write cleaner Pythoncode with strongtyping-pyoverload
With starting of Type-Hints in Python we can now better define what input we expect
we can say we only want to get a specific kind of Type, or we allow multiple once
deffunc_a(a: int):
...
# in python 3.10 we can also write `str | int` instead of Uniondeffunc(a: Union[str, int]):
...
the same works on class level too
classFoo:
deffunc_a(self, a: list):
...
# in python 3.10 we can also write `str | int` instead of Uniondeffunc(self, a: Union[list, tuple]):
ifisinstance(a, list):
...
ifisinstance(a, tuple):
...
wouldn't it not be nice to have a dedicated method for each parameter without renaming it
classFoo:
deffunc(self, a: str):
print("Called with `str`")
deffunc(self, a: list):
print("Called with `list`")
deffunc(self, a: tuple):
print("Called with `tuple`")
Python will raise no error if you do this but if you call the function
>>>foo=Foo()
>>>foo.func([1, 2, 3])
"Called with `tuple`">>>foo.func((1, 2, 3))
"Called with `tuple`"
Python will always use the latest definition for both cases
This is where the overload decorator from strongtyping-pyoverload comes into play
fromstrongtyping_pyoverloadimportoverloadclassFoo:
@overloaddeffunc(self, a: str):
print("Called with `str`")
@overloaddeffunc(self, a: list):
print("Called with `list`")
@overloaddeffunc(self, a: tuple):
print("Called with `tuple`")
>>>foo=Foo()
>>>foo.func("hello")
"Called with `str`">>>foo.func(list("hello"))
"Called with `list`">>>foo.func(tuple("hello"))
"Called with `tuple`"