Skip to content

Support for Range Types? #554

Closed
Closed

Description

@chang

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;

Activity

  1. robertvunabandi commented on Jul 10, 2019

    @robertvunabandi

    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.

  2. gvanrossum commented on Jul 10, 2019

    @gvanrossum
    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.

  3. gvanrossum commented on Jul 10, 2019

    @gvanrossum
    Member

    I propose to close this issue.

  4. ilevkivskyi commented on Jul 10, 2019

    @ilevkivskyi
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions