Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created May 25, 2024 04:17
Show Gist options
  • Save mypy-play/d040369d932e3864cdf2276820a9260d to your computer and use it in GitHub Desktop.
Save mypy-play/d040369d932e3864cdf2276820a9260d to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from typing import Literal, reveal_type
def sign(x: int) -> Literal[-1, 0, 1]:
"""Extracts the sign of x."""
s = -1 if x < 0 else (0 if x == 0 else 1)
reveal_type(s) # int
match s:
case -1 | 0 | 1:
reveal_type(s) # narrowed to Literal[-1, 0, 1]
return s
case _:
raise AssertionError("Unreachable.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment