Skip to content
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

Add special handling for typing.get_args #17784

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

Jordandev678
Copy link
Contributor

This PR adds special handling for typing.get_args when the input is a Union[Literal...] allowing it to return that type instead of the current behavior of returning Any. Adds the handling and related test cases for get_args with varying types.

This allows mypy to understand when it is used as a type guard.

from typing import Literal, get_args
type_alpha = Literal["a", "b", "c"]
strIn: str = "c"
if strIn in get_args(type_alpha):
    reveal_type(strIn)  # N: Revealed type is "Union[Literal['a'], Literal['b'], Literal['c']]"
else:
    reveal_type(strIn)  # N: Revealed type is "builtins.str"

Fixes #15106

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

Copy link
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

scipy (https://github.com/scipy/scipy)
+ scipy/signal/tests/test_short_time_fft.py:419: error: Argument "fft_mode" to "ShortTimeFFT" has incompatible type "str | int | None"; expected "Literal['twosided', 'centered', 'onesided', 'onesided2X']"  [arg-type]
+ scipy/signal/tests/test_short_time_fft.py:419: error: Argument "mfft" to "ShortTimeFFT" has incompatible type "str | int | None"; expected "int | None"  [arg-type]
+ scipy/signal/tests/test_short_time_fft.py:420: error: Argument "scale_to" to "ShortTimeFFT" has incompatible type "str | int | None"; expected "Literal['magnitude', 'psd'] | None"  [arg-type]
+ scipy/signal/tests/test_short_time_fft.py:420: error: Argument "phase_shift" to "ShortTimeFFT" has incompatible type "str | int | None"; expected "int | None"  [arg-type]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support type narrowing literals using typing.get_args()
1 participant