
On Mon, Apr 26, 2021 at 4:19 AM Shreyan Avigyan <pythonshreyan09@gmail.com> wrote:
I am aware of all those libraries that allows us to type check. But it would be nice to have this feature built-in. I'm not talking about modifying type annotation but introducing a new feature. Like,
def add(int a, int b): return a + b
If type is not provided then take in any parameter types. Like,
def example(c): print(c)
Why? Type annotations already exist. You're asking for something that requires brand new syntax and can already be done. Instead of writing it as if it's C, try writing it like this: @type_check def add(a: int, b: int) -> int: return a + b (I took the liberty of adding a return value annotation as well.) There are several existing libraries that can provide a decorator to do these sorts of run-time checks, or you can write your own. By the way: If you're writing checks like this, you have bigger problems than syntax. # Don't do this def add(a, b): if type(a) == int and type(b) == int: return a +b raise Exception("Error") Instead, all type checks should use isinstance, so that subclasses are allowed: def add(a, b): if not isinstance(a, int) or not isinstance(b, int): raise TypeError("Arguments must be integers") return a + b But it is far better, in most situations, to allow your function to be used by more types. Do you REALLY need to require that the numbers be integers, or is it okay for them to be other types of number? What if they're floats or Fractions that happen to be integers (eg 25.0 or 25/1)? Forcing precise types makes your function less useful in situations when it otherwise could be exactly what someone wants. ChrisA