-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Add support for simple lambda type guard #9890
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
Comments
Let’s wait for PEP 647 rather than inventing something new. |
(I think once we have PEP 647 we can add an overload to filter() to support
this.)
|
I don't see how this can be done with an overload, unless mypy learns to infer TypeGuards from lambdas (which doesn't necessarily seem the most straightforward) |
Hm... We already have this in builtins.pyi: @overload
def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ...
@overload
def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... If we add an overload like you proposed earlier in #9865 def filter(fn: Callable[[T1], TypeGuard[T2]], it: Iterable[T1]) -> Iterator[T2]: ... couldn't that be made to work? Not with a lambda, for sure -- you'd have to write a typeguard, e.g. def not_none(x: Optional[T]) -> TypeGuard[T]:
return x is not None (It works with a filter() function defined like that locally -- I haven't yet tried adding that line to typeshed.) |
Yes, sorry, I was talking specifically about lambdas since OP seemed specifically concerned about those. The typeshed overload should work for TypeGuard annotated functions :-) |
I've changed the priority to "low", since the easy workaround here is just to define the function using a (Note that the relevant overload was added to typeshed in python/typeshed#6726.) |
Feature
Consider the following code:
It would be nice if mypy was able to parse simple lambda functions like this one, and infer that
filtered
istyping.Iterator[builtins.int]
.Note that in this example, we use a simple none check, but this could work with more complicated checks:
Pitch
This is a fairly common idiom in Python.
Reasons why mypy might now want to do this:
The text was updated successfully, but these errors were encountered: