
Typeguard provides this functionality: https://typeguard.readthedocs.io/en/latest/userguide.html It's not perfect but that's because runtime type hints have lots of restrictions on what can be reasoned about them. But for simple and common cases it works very well. -- Damian (he / him) On Sun, Apr 25, 2021 at 9:38 AM Richard Damon <Richard@damon-family.org> wrote:
Think it like this. We have this code in Python :-
def add(a, b): return a + b
Here we are taking two arguments a, b and then returning a + b. But we can pass in instance of any class like str, int, float, dict, user-defined class, etc. But we only want to add int here. Here we can modify it to be,
def add(a, b): if type(a) == int and type(b) == int: return a +b raise Exception("Error")
In this example it's pretty easy to check if the arguments are int. But in real world programs as the functions become bigger and bigger it's very difficult to check arguments using an if statement. Therefore why not let
On 4/25/21 9:09 AM, Shreyan Avigyan wrote: the user specify what parameter types are gonna be? Like,
def add(int a, int b): return a + b
If instance of a different class is passed in then raise a TypeError
perhaps? If parameter types are not given then let the parameter accept any kind of class instance.
This kind of functionality will minimize a lot of if statements related
to parameter types and arguments.
Thanking you, With Regards
Well, in Python with type annotations that would be spelled:
def add(a: int, b: int):
return a + b
but the one difference is that, at least by default, that requirement is advisorary only. You can run a static type checker like mypy at it will see if it can deduce a case where you pass a non-int to the function.
You could also import a module into your module that will actually do the check at run-time (I don't know of one, but there probably is one) maybe needing the function to be decorated to request the type checking.
-- Richard Damon
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/7DCIKC... Code of Conduct: http://python.org/psf/codeofconduct/