Skip to content

Support for Range Types? #554

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
chang opened this issue Apr 23, 2018 · 4 comments
Closed

Support for Range Types? #554

chang opened this issue Apr 23, 2018 · 4 comments

Comments

@chang
Copy link

chang commented Apr 23, 2018

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:

from typing import RangeType, Tuple

ZipCode = RangeType(low=501, high=99950):

def get_gps_coordinate(code: ZipCode) -> Tuple[float, float]:
    ...

Another language that has range types is Ada, which lets you define range types like so:

type ZipCode is range 00501 .. 99950;
@robertvunabandi
Copy link

Interesting. I feel like a range type is a bit too specific. What it's essentially doing here is to make sure that in:

from typing import RangeType, Tuple
ZipCode = RangeType(low=501, high=99950):
def get_gps_coordinate(code: ZipCode) -> Tuple[float, float]:
    pass

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.

@gvanrossum
Copy link
Member

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 NewType plus a dynamic range check.

@gvanrossum
Copy link
Member

I propose to close this issue.

@ilevkivskyi
Copy link
Member

I propose to close this issue.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants