Skip to content

Proposal: Allow using final literal immutable containers as Literal #8689

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
antonagestam opened this issue Apr 17, 2020 · 1 comment
Closed

Comments

@antonagestam
Copy link
Contributor

antonagestam commented Apr 17, 2020

I've found many situations where it would have been preferable to be able to use a Literal at runtime, or to be able to dynamically check if a value is in it. I'm proposing that a frozenset (and perhaps other immutable containers) should be interpreted as a Literal if defined as a literal, used as a type hint, and perhaps required to be defined with ClassVar or Final. This would allow sharing definitions of valid choices between runtime and static type checking.

Further I'm proposing to add type-guards for ... in ... statements using these Literal-like collections.

An example of how I'm thinking this should work:

AllowedMethod: Final = frozenset({"POST", "GET", "PUT", "PATCH", "HEAD"})


# This should work as if defined as method: Literal["POST", "GET", "PUT", "PATCH", "HEAD"]
def request(method: AllowedMethod) -> Response:
    ...


def do_thing(method: str) -> Response:
    # Testing for membership should narrow `method` to `AllowedMethod`
    if method in AllowedMethod:
        request(method)
@antonagestam antonagestam reopened this Apr 17, 2020
@antonagestam antonagestam changed the title Proposal: Allow using frozenset in place of Literal Proposal: Allow using literal immutable containers as Literal Apr 17, 2020
@antonagestam antonagestam changed the title Proposal: Allow using literal immutable containers as Literal Proposal: Allow using final literal immutable containers as Literal Apr 17, 2020
@antonagestam
Copy link
Contributor Author

I'm closing this as I've found solving this using phantom types to work well. Here's an example using ISO country codes if anyone stumbles upon this issue: https://github.com/antonagestam/phantom-types/blob/main/phantom/ext/iso3166.py

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

1 participant