Skip to content

Allow float("inf") and float("-inf") in literals #1160

Open
@antonagestam

Description

@antonagestam

I have been frequently using positive and negative infinity as default values for values that should otherwise be ints. Because of Python's duck typing this is a convenient pattern that sometimes allows reducing some special-casing logic.

def less_than(value: int, limit: int | None) -> bool:
    if limit is None:
        return True
    return value < limit

vs

def less_than(value: int, limit: int | Literal[float("inf")]) -> bool:
    return value < limit

Would it be feasible to special-case the expressions float("inf") and float("-inf") and make type-checkers regard them as literal values, even though they aren't strictly speaking language-level literals?


For posterity, PEP 586 mentions this with:

Representing Literals of infinity or NaN in a clean way is tricky; real-world APIs are unlikely to vary their behavior based on a float parameter.

So I guess what I'm asking here is: am I an odd duckling or could it be worth considering +/- infinity as legal values in literal types?

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions