On Fri, 7 Aug 2020 at 22:46, Ricky Teachey email@example.com wrote:
This was inspired by a tweet today from Brandon Rhodes. I looked for something like it on the mypy issues page and didn't find anything.
Would it make good semantic sense- and be useful- to specify valid numerical ranges using slices and type-hint syntax? My suggestion would be to, at minimum, provide this functionality for int and float.
Consider that currently we have:
x: int # this means "all ints", today x: float # this means "all floating point numbers", today
Idea in a nutshell would be for the following type declarations to mean:
x: int[0:] # any ints greater than or equal to zero would match, others would fail x: int[:101] # any ints less than 101 match x: int[0:101:2] # even less than 101
I suspect the biggest issue with this is that it's likely to be extremely hard (given the dynamic nature of Python) to check such type assertions statically. Even in statically typed languages, you don't often see range-based types like this. And type assertions don't do runtime checks, so if they can't be usefully checked statically, they probably aren't going to be of much benefit (documentation is basically all).