python / python/typing

Allow `float("inf")` and `float("-inf")` in literals

Open
#1,160 21 comments 23 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

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?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading PEP 586's discussion of illegal Literal parameters and the 21 comments on this issue. Determine whether the typing community has reached a decision on treating float("inf") and float("-inf") as literal values; done would require an agreed specification and identified type-checker changes, which the issue does not provide.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.