Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions python-type-checking/README.md
Original file line number Diff line number Diff line change
@@ -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
```
8 changes: 3 additions & 5 deletions python-type-checking/dogs_002.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion python-type-checking/game_001.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 4 additions & 5 deletions python-type-checking/game_002.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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])

Expand All @@ -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)

Expand Down
3 changes: 1 addition & 2 deletions python-type-checking/game_003.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
39 changes: 19 additions & 20 deletions python-type-checking/hearts.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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):
Expand All @@ -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")])
Expand All @@ -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([])
Expand All @@ -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)
Expand All @@ -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))
Expand Down Expand Up @@ -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"))
Expand All @@ -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)
Expand All @@ -199,25 +200,23 @@ 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)
start_idx = self.players.index(start)
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()}


Expand Down
10 changes: 10 additions & 0 deletions python-type-checking/jokes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# jokes.py

import pyjokes


def tell_joke(category: str) -> str:
return pyjokes.get_joke(category=category)


print(tell_joke("neutral"))
20 changes: 0 additions & 20 deletions python-type-checking/parse.pyi

This file was deleted.

23 changes: 0 additions & 23 deletions python-type-checking/parse_name.py

This file was deleted.

4 changes: 4 additions & 0 deletions python-type-checking/pyjokes.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# pyjokes.pyi

def get_joke(language: str = ..., category: str = ...) -> str: ...
def get_jokes(language: str = ..., category: str = ...) -> list[str]: ...
4 changes: 4 additions & 0 deletions python-type-checking/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mypy==2.4.1
pyjokes==0.8.3
tabulate==0.10.0
types-tabulate==0.10.0.20261006
5 changes: 5 additions & 0 deletions python-type-checking/table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# table.py

from tabulate import tabulate

print(tabulate([["Python", 1991], ["Mypy", 2012]], headers=["Name", "Year"]))
Loading