Skip to content

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

Closed
@antonagestam

Description

@antonagestam

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)

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