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
{{ message }}
Repository navigation
Idea: short-circuit analysis with if <platform-check>: return #5964
I'm adding OS-specific typechecking to a large Python app, and we have a fair number of files and functions that mix OS versions. Currently, mypy only does limited analysis with platform/version/constants to figure out which lines it shouldn't check. With that limited analysis, it's possible to add OS-specific typechecking to the app, but it'll make the code a bit messier.
I'd like to get your feedback on two ideas that would make adding OS-specific typechecking easier.
For if statements where the expression is a mypy-constant, short-circuit if there's a return statement one-level deep in the body of the if. (Currently, the inner bodies of the if are conditionally checked, and return doesn't short-circuit checking.)
E.g.
# flags: --always-false=IS_WINDOWSifIS_WINDOWS:
importwin_specific_importdefsome_fun_broken() ->int:
ifnotIS_WINDOWS:
return1# checked# The rest of this function is analyzed even though we returned above. # Blows up since `win_specific_import` isn't definedreturnwin_specific_import.something()
defsome_fun_fixed() ->int:
ifnotIS_WINDOWS:
return1# checkedelse:
# Not analyzed because this is in the `else` part of the `if` statementreturnwin_specific_import.something() # Works
We use the if not IS_WINDOWS: return pattern a fair amount in our codebase, and it would be nice if mypy supported that.
I'm not sure how we'd implement that in mypy, though. Maybe we can scan for a return one-level deep in if statement bodies which have a mypy-constant expression and mark the rest of the function as unreachable.
It would be convenient if we ignored the rest of the function body if the first statement in it is a mypy-constant assert. I don't think we'd want to look for asserts elsewhere in the function block, though, even though that would make it a magical special-case.
Both of these ideas sound fine. I think the strategy in #5894 (which implements #5308) would extend well in both cases (though the first case looks like it would be a bit more complicated).
Activity
gvanrossum commentedon Nov 28, 2018
Both of these ideas sound fine. I think the strategy in #5894 (which implements #5308) would extend well in both cases (though the first case looks like it would be a bit more complicated).