-
Notifications
You must be signed in to change notification settings - Fork 767
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
Type check fails: "if None" condition ignored within lambda #261
Comments
In most cases, Pylance uses code flow analysis to determine whether a type can be narrowed from its original declared type. Using your example above, the type of This is the same approach I've seen used in other type checkers in other languages. For example, TypeScript uses this same approach for captured variables used in lambdas or locally-defined functions. Consider this small variation on your example. In this case, s is getting reassigned after the lambda is declared and after
In the few cases where I've encountered this pattern in my team's code base, I've easily worked around it using the technique in your first example — by defining a new local variable that has the correct type. An alternative workaround involves the use of an assert statement, but that requires you to switch from a lambda to a local function, which is definitely more verbose. It does has the advantage of allowing the input parameters to be explicitly annotated, which isn't possible with the lambda syntax.
And of course, you can always suppress type-related errors using a "# type: ignore" comment or a "cast" call, but I tend to use those as a last resort. |
Dear Eric, I stumbled upon this issue while presenting Pylance to my team. It's really an amazing tool and I'm promoting its usage within the company. The issue can be closed from my side. Should I close it? |
I found a way to handle type narrowing of local variables and parameters captured by inner-scoped functions and lambdas, so the above workaround will no longer be necessary in this case. |
This issue has been fixed in version 2021.9.4, which we've just released. You can find the changelog here: https://github.com/microsoft/pylance-release/blob/main/CHANGELOG.md#202194-29-september-2021 |
Environment data
Expected behaviour
Pylance correctly does not report any error whithin this function.
s_not_none
is correctly inferred to be of typestr
However in the following function
Pylance says that
Argument of type "str | None" cannot be assigned to parameter "suffix" of type "str | Tuple[Text, ...]" in function "endswith"
. The expected behavior is that no error should be reported.Actual behaviour
An error is reported by Pylance saying that s may be None, even though there is a check for it.
Pylance says that
Argument of type "str | None" cannot be assigned to parameter "suffix" of type "str | Tuple[Text, ...]" in function "endswith"
The text was updated successfully, but these errors were encountered: