-
Notifications
You must be signed in to change notification settings - Fork 771
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
Deduced actual type of variable not used in lambda context #1016
Comments
Type narrowing is not applied to variables captured within a lambda context because captured symbols can be reassigned a new value (with a different type) by the time the lambda is executed. In this particular case, it is safe, but in general a type checker cannot make this assumption. The workaround is to assign the narrowed value to a local variable that has a non-union callable type. from typing import Callable
def int_to_value(value: 'int | Callable') -> 'dict':
if isinstance(value, int):
return dict(hex="0x{:X}".format(value))
else:
callable_value = value
return dict(hex=lambda: "0x{:X}".format(callable_value())) |
Perfect, thanks for really fast response, it works fine with this workround. |
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 |
Works great. Thanks! |
Environment data
Expected behaviour
Deduced actual type (reduced by isinstance's) is recognised in lambda context.
Actual behaviour
When typed argument is used inside lambda, the original argument type is used instead of the one reduced by isinstance's.
Warning:
Logs
This is reported from a company notebook, so I cannot provide logs (data collection restrictions).
Code Snippet / Additional information
This fails, see the last line and a
value()
call.:Please note that the following works correctly:
The text was updated successfully, but these errors were encountered: