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
Is it possible to define a range of integers as a type? Sometimes we might want to constrain an input to a certain range of values.
For example, a US ZIP code must be a 5 digit value. I didn't know this before to opening the issue, but apparently the lowest ZIP code is in Holtsville, New York (00501) and the highest ZIP code is in Ketchikan, Alaska (99950). It would be great if we could define a type like this:
code must be in the range [501, 99950]. This sounds like something you check in code (maybe with an assert_valid_range(code) method) because there's no clear way a linter would know that code is in that range without running the code. Like, I don't think there is a RangeType even in statically typed language like Java, but correct me if I'm wrong.
OK, for short ranges people can use unions of literal types -- Grade = Literal[1, 2, 3, 4, 5], and for array dimensions we will have integer generics (hopefully this year). The general range types proposed here are indeed very tricky.
Activity
robertvunabandi commentedon Jul 10, 2019
Interesting. I feel like a range type is a bit too specific. What it's essentially doing here is to make sure that in:
codemust be in the range[501, 99950]. This sounds like something you check in code (maybe with anassert_valid_range(code)method) because there's no clear way a linter would know thatcodeis in that range without running the code. Like, I don't think there is aRangeTypeeven in statically typed language like Java, but correct me if I'm wrong.gvanrossum commentedon Jul 10, 2019
IIRC Pascal had range types (
type weekday = 1..7;), and Ada made an art of it.There are lots of edge cases though, since the common arithmetic operations aren't closed on range types.
In the PEP 484 world your best alternative is
NewTypeplus a dynamic range check.gvanrossum commentedon Jul 10, 2019
I propose to close this issue.
ilevkivskyi commentedon Jul 10, 2019
OK, for short ranges people can use unions of literal types --
Grade = Literal[1, 2, 3, 4, 5], and for array dimensions we will have integer generics (hopefully this year). The general range types proposed here are indeed very tricky.