Skip to content

Instantly share code, notes, and snippets.

@mahenzon
Created February 17, 2024 19:33
Show Gist options
  • Save mahenzon/930434b1317a1d1d7ef7653d1a094ea0 to your computer and use it in GitHub Desktop.
Save mahenzon/930434b1317a1d1d7ef7653d1a094ea0 to your computer and use it in GitHub Desktop.
Never and NoReturn Annotations Python examples
def get_num() -> int:
return 42
def get_word() -> str:
return "spam"
def main() -> None:
num = get_num()
print(num**2)
word = get_word()
print(word.title())
if __name__ == "__main__":
main()
from typing import NoReturn
def abort(reason: str) -> NoReturn:
raise ValueError(f"Reason: {reason}")
# def main() -> None:
# print("Hello World!")
# res: str = abort("Some error")
# print(res.title())
# print("Bye!")
def main() -> None:
print("Hello World!")
abort("Some error")
print("Bye!")
if __name__ == "__main__":
main()
from typing import Never, NoReturn, assert_never
from enum import StrEnum, auto
class TrafficLight(StrEnum):
red = auto()
yellow = auto()
green = auto()
def log_unexpected_action(action: Never) -> None:
print("Unexpected action", action)
def raise_on_unexpected_action(action: Never) -> NoReturn:
raise ValueError(f"Unexpected action: {action}")
def take_action(light: TrafficLight) -> None:
if light is TrafficLight.red:
print("Please wait.")
elif light is TrafficLight.green:
print("You can go")
elif light is TrafficLight.yellow:
print("Be extra cautious!")
else:
# log_unexpected_action(light)
# raise_on_unexpected_action(light)
assert_never(light)
def main() -> None:
for light in TrafficLight:
print("+ Light is", light)
take_action(light)
if __name__ == "__main__":
main()
from typing import assert_never
def check_count(count: int) -> None:
if count > 0:
print("The count is greater than zero")
elif count == 0:
print("The count is equal to zero")
elif count < 0:
print("The count is less than zero")
elif isinstance(count, int):
print("The count is an integer, this code is never reachable")
else:
assert_never(count)
def check_count_via_match(count: int) -> None:
match count:
case c if c > 0:
print("The count is greater than zero")
case c if c == 0:
print("The count is equal to zero")
case c if c < 0:
print("The count is less than zero")
case int():
print("The count is int, but this is never reachable")
case c:
assert_never(c)
def main() -> None:
check_count_via_match(1)
check_count_via_match(0)
check_count_via_match(-1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment