-
Notifications
You must be signed in to change notification settings - Fork 240
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
Types for "truthy" and "falsy" values #1606
Comments
In typed code I would prefer checking explicitly for None instead of all falsy values: def run_until_not_none[T](fn: Callable[[], T | None], num_tries: int = 5) -> T:
for _ in range(num_tries):
if (res := fn()) is not None:
return res
Exception('Giving up.') This can already be typed and is less likely to lead to surprises. |
Would this work for your case? |
I don't think it addresses my use case. The type returned by |
If I wrote that part of the application now, I would definitely use this approach. But I have found existing usages that make use of the fact that the function will be re-run on return values Another case where these types could be useful is when typing functions that have behavior similar to the |
from typing import Literal, Protocol
class Truthy(Protocol):
def __bool__(self) -> Literal[True]: ...
class Falsy(Protocol):
def __bool__(self) -> Literal[False]: ... This doesn't really appear to work in pyright or mypy however, since But I would seriously question the value of making something like this work, since excluding a single literal from a type is usually not that helpful ( Of course you could write a couple of simple |
My request stems purely from typing existing code. Partly, that code is a result of how Python employs the concept of truthy/falsy in boolean contexts. Because of typing ergonomics, I usually refrain from relying on that concept (e.g. |
It may be helpful to note that |
I found this function in our codebase and I'm trying to type it:
The function repeatedly calls a callable without arguments until it returns a "truthy" value. Then it returns that value. Easy enough:
This is correct but too restrictive. Usages like this don't work:
I can hack it to make it work:
Does it make sense to add official
Truthy
andFalsy
types to the standard library?Maybe a
Truthy
type would also make sense.Truthy
can't be defined as a type alias of existing types, but could probably also be useful sometimes, e.g. to type the following function:From thinking about it for a few minutes, I think
Falsy
would be more often useful thanTruthy
, at least in combination with the current typing features.If there's an intersection type constructor at some point, the above examples could be written like this instead, which might be easier to understand:
2024-11-25
&
instead ofIntersection[]
in example using proposed intersection types.The text was updated successfully, but these errors were encountered: