diff --git a/python-type-checking/README.md b/python-type-checking/README.md index fbe61a01ba..1386fb6c9f 100644 --- a/python-type-checking/README.md +++ b/python-type-checking/README.md @@ -1,4 +1,36 @@ -# The Ultimate Guide to Python Type Checking +# Python Type Checking (Guide) -Code examples from the [The Ultimate Guide to Python Type Checking](https://realpython.com/python-type-checking/) tutorial on [Real Python](https://realpython.com/). +Code examples from the [Python Type Checking (Guide)](https://realpython.com/python-type-checking/) tutorial on [Real Python](https://realpython.com/). +## Setup + +You need Python 3.11 or later. Create and activate a virtual environment, then install the pinned dependencies: + +```console +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +## Usage + +The files follow the tutorial's sections: + +- `game_001.py`, `game_002.py`, and `game_003.py` are the stages of the card game, from plain functions with no type hints to the object-oriented version. +- `dogs_001.py` and `dogs_002.py` show how to annotate methods that return an instance of their own class, first with string annotations and then with `typing.Self`. +- `hearts.py` is the full, type-hinted Hearts game. +- `jokes.py` and `pyjokes.pyi` are the untyped-library and stub-file examples. +- `table.py` is the Typeshed example. + +Run any of the programs with Python, and check them with mypy: + +```console +(venv) $ python hearts.py GeirArne Aldren Joanna Brad +(venv) $ mypy hearts.py +``` + +To let mypy use the `pyjokes.pyi` stub file, point `MYPYPATH` to this folder: + +```console +(venv) $ MYPYPATH=. mypy jokes.py +``` diff --git a/python-type-checking/dogs_002.py b/python-type-checking/dogs_002.py index 71c139a3a8..fecd9ddb41 100644 --- a/python-type-checking/dogs_002.py +++ b/python-type-checking/dogs_002.py @@ -1,9 +1,7 @@ # dogs.py from datetime import date -from typing import Type, TypeVar - -TAnimal = TypeVar("TAnimal", bound="Animal") +from typing import Self class Animal: @@ -12,10 +10,10 @@ def __init__(self, name: str, birthday: date) -> None: self.birthday = birthday @classmethod - def newborn(cls: Type[TAnimal], name: str) -> TAnimal: + def newborn(cls, name: str) -> Self: return cls(name, date.today()) - def twin(self: TAnimal, name: str) -> TAnimal: + def twin(self, name: str) -> Self: cls = self.__class__ return cls(name, self.birthday) diff --git a/python-type-checking/game_001.py b/python-type-checking/game_001.py index 6c999fd246..2ebf38a135 100644 --- a/python-type-checking/game_001.py +++ b/python-type-checking/game_001.py @@ -23,7 +23,7 @@ def play(): """Play a 4-player card game""" deck = create_deck(shuffle=True) names = "P1 P2 P3 P4".split() - hands = {n: h for n, h in zip(names, deal_hands(deck), strict=False)} + hands = {n: h for n, h in zip(names, deal_hands(deck))} for name, cards in hands.items(): card_str = " ".join(f"{s}{r}" for (s, r) in cards) diff --git a/python-type-checking/game_002.py b/python-type-checking/game_002.py index 4cf3a66e3f..b91d3d8989 100644 --- a/python-type-checking/game_002.py +++ b/python-type-checking/game_002.py @@ -1,13 +1,12 @@ # game.py import random -from typing import List, Tuple SUITS = "♠ ♡ ♢ ♣".split() RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split() -Card = Tuple[str, str] -Deck = List[Card] +Card = tuple[str, str] +Deck = list[Card] def create_deck(shuffle: bool = False) -> Deck: @@ -18,7 +17,7 @@ def create_deck(shuffle: bool = False) -> Deck: return deck -def deal_hands(deck: Deck) -> Tuple[Deck, Deck, Deck, Deck]: +def deal_hands(deck: Deck) -> tuple[Deck, Deck, Deck, Deck]: """Deal the cards in the deck into four hands""" return (deck[0::4], deck[1::4], deck[2::4], deck[3::4]) @@ -40,7 +39,7 @@ def play() -> None: """Play a 4-player card game""" deck = create_deck(shuffle=True) names = "P1 P2 P3 P4".split() - hands = {n: h for n, h in zip(names, deal_hands(deck), strict=False)} + hands = {n: h for n, h in zip(names, deal_hands(deck))} start_player = choose(names) turn_order = player_order(names, start=start_player) diff --git a/python-type-checking/game_003.py b/python-type-checking/game_003.py index 853d01015a..99e43b0316 100644 --- a/python-type-checking/game_003.py +++ b/python-type-checking/game_003.py @@ -53,8 +53,7 @@ def __init__(self, *names): deck = Deck.create(shuffle=True) self.names = (list(names) + "P1 P2 P3 P4".split())[:4] self.hands = { - n: Player(n, h) - for n, h in zip(self.names, deck.deal(4), strict=False) + n: Player(n, h) for n, h in zip(self.names, deck.deal(4)) } def play(self): diff --git a/python-type-checking/hearts.py b/python-type-checking/hearts.py index 4f93f572e2..bb31ca1f19 100644 --- a/python-type-checking/hearts.py +++ b/python-type-checking/hearts.py @@ -1,9 +1,10 @@ # hearts.py +from collections import Counter +from collections.abc import Sequence import random import sys -from collections import Counter -from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, overload +from typing import Any, overload class Card: @@ -39,7 +40,7 @@ def __repr__(self) -> str: class Deck(Sequence[Card]): - def __init__(self, cards: List[Card]) -> None: + def __init__(self, cards: list[Card]) -> None: self.cards = cards @classmethod @@ -54,11 +55,11 @@ def play(self, card: Card) -> None: """Play one card by removing it from the deck""" self.cards.remove(card) - def deal(self, num_hands: int) -> Tuple["Deck", ...]: + def deal(self, num_hands: int) -> tuple["Deck", ...]: """Deal the cards in the deck into a number of hands""" return tuple(self[i::num_hands] for i in range(num_hands)) - def add_cards(self, cards: List[Card]) -> None: + def add_cards(self, cards: list[Card]) -> None: """Add a list of cards to the deck""" self.cards += cards @@ -71,7 +72,7 @@ def __getitem__(self, key: int) -> Card: ... @overload def __getitem__(self, key: slice) -> "Deck": ... - def __getitem__(self, key: Union[int, slice]) -> Union[Card, "Deck"]: + def __getitem__(self, key: int | slice) -> "Card | Deck": if isinstance(key, int): return self.cards[key] elif isinstance(key, slice): @@ -85,11 +86,11 @@ def __repr__(self) -> str: class Player: - def __init__(self, name: str, hand: Optional[Deck] = None) -> None: + def __init__(self, name: str, hand: Deck | None = None) -> None: self.name = name self.hand = Deck([]) if hand is None else hand - def playable_cards(self, played: List[Card], hearts_broken: bool) -> Deck: + def playable_cards(self, played: list[Card], hearts_broken: bool) -> Deck: """List which cards in hand are playable this round""" if Card("♣", "2") in self.hand: return Deck([Card("♣", "2")]) @@ -100,7 +101,7 @@ def playable_cards(self, played: List[Card], hearts_broken: bool) -> Deck: playable = Deck([c for c in playable if c.suit != "♡"]) return playable or Deck(self.hand.cards) - def non_winning_cards(self, played: List[Card], playable: Deck) -> Deck: + def non_winning_cards(self, played: list[Card], playable: Deck) -> Deck: """List playable cards that are guaranteed to not win the trick""" if not played: return Deck([]) @@ -109,7 +110,7 @@ def non_winning_cards(self, played: List[Card], playable: Deck) -> Deck: best_card = max(c for c in played if c.suit == lead) return Deck([c for c in playable if c < best_card or c.suit != lead]) - def play_card(self, played: List[Card], hearts_broken: bool) -> Card: + def play_card(self, played: list[Card], hearts_broken: bool) -> Card: """Play a card from a cpu player's hand""" playable = self.playable_cards(played, hearts_broken) non_winning = self.non_winning_cards(played, playable) @@ -136,7 +137,7 @@ def __repr__(self) -> str: class HumanPlayer(Player): - def play_card(self, played: List[Card], hearts_broken: bool) -> Card: + def play_card(self, played: list[Card], hearts_broken: bool) -> Card: """Play a card from a human player's hand""" playable = sorted(self.playable_cards(played, hearts_broken)) p_str = " ".join(f"{n}: {c}" for n, c in enumerate(playable)) @@ -175,10 +176,10 @@ def play(self) -> None: winners = [n for n in self.names if score[n] == min(score.values())] print(f"\n{' and '.join(winners)} won the game") - def play_round(self) -> Dict[str, int]: + def play_round(self) -> dict[str, int]: """Play a round of the Hearts card game""" deck = Deck.create(shuffle=True) - for player, hand in zip(self.players, deck.deal(4), strict=False): + for player, hand in zip(self.players, deck.deal(4)): player.hand.add_cards(hand.cards) start_player = next( p for p in self.players if p.has_card(Card("♣", "2")) @@ -188,7 +189,7 @@ def play_round(self) -> Dict[str, int]: # Play cards from each player's hand until empty while start_player.hand: - played: List[Card] = [] + played: list[Card] = [] turn_order = self.player_order(start=start_player) for player in turn_order: card = player.play_card(played, hearts_broken=hearts) @@ -199,7 +200,7 @@ def play_round(self) -> Dict[str, int]: hearts = hearts or any(c.suit == "♡" for c in played) return self.count_points(tricks) - def player_order(self, start: Optional[Player] = None) -> List[Player]: + def player_order(self, start: Player | None = None) -> list[Player]: """Rotate player order so that start goes first""" if start is None: start = random.choice(self.players) @@ -207,17 +208,15 @@ def player_order(self, start: Optional[Player] = None) -> List[Player]: return self.players[start_idx:] + self.players[:start_idx] @staticmethod - def trick_winner(trick: List[Card], players: List[Player]) -> Player: + def trick_winner(trick: list[Card], players: list[Player]) -> Player: lead = trick[0].suit valid = [ - (c.value, p) - for c, p in zip(trick, players, strict=False) - if c.suit == lead + (c.value, p) for c, p in zip(trick, players) if c.suit == lead ] return max(valid)[1] @staticmethod - def count_points(tricks: Dict[str, Deck]) -> Dict[str, int]: + def count_points(tricks: dict[str, Deck]) -> dict[str, int]: return {n: sum(c.points for c in cards) for n, cards in tricks.items()} diff --git a/python-type-checking/jokes.py b/python-type-checking/jokes.py new file mode 100644 index 0000000000..c612e19420 --- /dev/null +++ b/python-type-checking/jokes.py @@ -0,0 +1,10 @@ +# jokes.py + +import pyjokes + + +def tell_joke(category: str) -> str: + return pyjokes.get_joke(category=category) + + +print(tell_joke("neutral")) diff --git a/python-type-checking/parse.pyi b/python-type-checking/parse.pyi deleted file mode 100644 index 3a252f6eb7..0000000000 --- a/python-type-checking/parse.pyi +++ /dev/null @@ -1,20 +0,0 @@ -# parse.pyi - -from typing import Mapping, Optional, Sequence, Tuple, Union - -class Result: - def __init__( - self, - fixed: Sequence[str], - named: Mapping[str, str], - spans: Mapping[int, Tuple[int, int]], - ) -> None: ... - def __getitem__(self, item: Union[int, str]) -> str: ... - def __repr__(self) -> str: ... - -def parse( - format: str, - string: str, - evaluate_result: bool = ..., - case_sensitive: bool = ..., -) -> Optional[Result]: ... diff --git a/python-type-checking/parse_name.py b/python-type-checking/parse_name.py deleted file mode 100644 index 36a07669af..0000000000 --- a/python-type-checking/parse_name.py +++ /dev/null @@ -1,23 +0,0 @@ -# parse_name.py - -import parse - - -def parse_name(text: str) -> str: - patterns = ( - "my name is {name}", - "i'm {name}", - "i am {name}", - "call me {name}", - "{name}", - ) - for pattern in patterns: - result = parse.parse(pattern, text) - if result: - return result["name"] - return "" - - -answer = input("What is your name? ") -name = parse_name(answer) -print(f"Hi {name}, nice to meet you!") diff --git a/python-type-checking/pyjokes.pyi b/python-type-checking/pyjokes.pyi new file mode 100644 index 0000000000..8651f8df2d --- /dev/null +++ b/python-type-checking/pyjokes.pyi @@ -0,0 +1,4 @@ +# pyjokes.pyi + +def get_joke(language: str = ..., category: str = ...) -> str: ... +def get_jokes(language: str = ..., category: str = ...) -> list[str]: ... diff --git a/python-type-checking/requirements.txt b/python-type-checking/requirements.txt new file mode 100644 index 0000000000..07dd20a517 --- /dev/null +++ b/python-type-checking/requirements.txt @@ -0,0 +1,4 @@ +mypy==2.4.1 +pyjokes==0.8.3 +tabulate==0.10.0 +types-tabulate==0.10.0.20261006 diff --git a/python-type-checking/table.py b/python-type-checking/table.py new file mode 100644 index 0000000000..ded4b9631c --- /dev/null +++ b/python-type-checking/table.py @@ -0,0 +1,5 @@ +# table.py + +from tabulate import tabulate + +print(tabulate([["Python", 1991], ["Mypy", 2012]], headers=["Name", "Year"]))