You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hmm my first instinct is that this is intentional because mypy tries not to persist type narrowing into callbacks (which it cannot track the lifetimes of). But moving the lambda out wouldn't fix this in that case...
In the original sample, the code is in the global scope, and it's not safe for a type checker to assume that m retains its narrowed value within the lambda because variables in the global scope can be modified outside of the module. Variables within a local scope cannot be modified outside of the local scope, so a type checker can prove that m is not reassigned. Pyright makes the same assumption here. So I don't think this is a bug.
I'm not sure why mypy retains the narrowed type when the lambda is moved outside of the call. I don't see how that makes it safe from a type perspective. This could be a bug.
Yes, what Eric mentions above is indeed a bug, lambda return expr is handled in a wrong scope.
x: int|NoneifxisnotNone:
bad=lambda: reveal_type(x) # N: Revealed type is "builtins.int"defbad_fn():
reveal_type(x) # N: Revealed type is "Union[builtins.int, None]"return-x# E: Unsupported operand type for unary - ("int | None") [operator]
Currently def functions use a new instance of binder and copy everything "safe" from global scope into it, and lambdas do not undergo similar treatment. This is a fairly difficult problem to fix.
Consider the following testcase:
I expect this to pass type checking successfully, but mypy instead complains about the map line as follows:
The bug only seems to happen if the lambda appears directly inside the call to map. E.g. if I pre-declare it as follows:
then this type-checks OK. My environment is as follows:
The text was updated successfully, but these errors were encountered: