Skip to content
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

Semaphore's value argument #12147

Open
multimeric opened this issue Jun 17, 2024 · 3 comments
Open

Semaphore's value argument #12147

multimeric opened this issue Jun 17, 2024 · 3 comments

Comments

@multimeric
Copy link

Currently we assume that the semaphore's value must be an integer:

_value: int
_waiters: deque[Future[Any]] | None
if sys.version_info >= (3, 10):
def __init__(self, value: int = 1) -> None: ...
else:
def __init__(self, value: int = 1, *, loop: AbstractEventLoop | None = None) -> None: ...

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.

@JelleZijlstra
Copy link
Member

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.

@multimeric
Copy link
Author

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

@srittau
Copy link
Collaborator

srittau commented Jun 17, 2024

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.

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

3 participants