typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Semaphore's value argument

Open multimeric opened this issue 1 year ago • 3 comments

Currently we assume that the semaphore's value must be an integer: https://github.com/python/typeshed/blob/1af9de664f41b51bd3b71dac349564c5c25df810/stdlib/asyncio/locks.pyi#L88-L93

Generally this is correct, but I had a use case where I wanted to disable the semaphore without restructuring my code, so I used float("inf") as the value to ensure that it never unlocks. This works perfectly fine, because the only operations that value needs to support are:

  • Adding 1
  • Subtracting 1
  • Comparing to 0

The infinity float value does all of these fine. So I therefore wonder if we should make this type be int | Literal[math.inf]? I agree that general floats are not a good idea because they will get below 0 without triggering the wait.

multimeric avatar Jun 17 '24 01:06 multimeric

I therefore wonder if we should make this type be int | Literal[math.inf]?

Unfortunately the type system does not allow this; float is not an allowed literal type. Cross-linking python/typing#1160.

JelleZijlstra avatar Jun 17 '24 03:06 JelleZijlstra

Wow, I didn't know that. Dare I suggest int | float then?

multimeric avatar Jun 17 '24 03:06 multimeric

I'm honestly wary to allow arbitrary floats here as using them could lead to bugs due to floating point math. I would suggest to use a big int instead, e.g. 2**64-1.

srittau avatar Jun 17 '24 14:06 srittau