From 99aa7da6a2a914a2285ce32453130732b5eddc6d Mon Sep 17 00:00:00 2001 From: Vintubin Date: Tue, 24 Nov 2026 21:09:26 +0500 Subject: [PATCH] perf: use slots for Piece, Move, _BoardState and streamline _remove_piece_at --- chess/__init__.py | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/chess/__init__.py b/chess/__init__.py index e62de8cbb..fae8a58b8 100644 --- a/chess/__init__.py +++ b/chess/__init__.py @@ -747,7 +747,7 @@ def between(a: Square, b: Square) -> Bitboard: FEN_CASTLING_REGEX = re.compile(r"^(?:-|[KQABCDEFGH]{0,2}[kqabcdefgh]{0,2})\Z") -@dataclasses.dataclass(frozen=True) +@dataclasses.dataclass(frozen=True, slots=True) class Piece: """A piece with type and color.""" @@ -802,7 +802,7 @@ def from_symbol(cls, symbol: str) -> Piece: ] -@dataclasses.dataclass(unsafe_hash=True) +@dataclasses.dataclass(unsafe_hash=True, slots=True) class Move: """ Represents a move from a square to a square and possibly the promotion @@ -1193,21 +1193,28 @@ def is_pinned(self, color: Color, square: Square) -> bool: return self.pin_mask(color, square) != BB_ALL def _remove_piece_at(self, square: Square) -> PieceType | None: - piece_type = self.piece_type_at(square) mask = BB_SQUARES[square] + if not self.occupied & mask: + return None - if piece_type == PAWN: + if self.pawns & mask: self.pawns ^= mask - elif piece_type == KNIGHT: + piece_type = PAWN + elif self.knights & mask: self.knights ^= mask - elif piece_type == BISHOP: + piece_type = KNIGHT + elif self.bishops & mask: self.bishops ^= mask - elif piece_type == ROOK: + piece_type = BISHOP + elif self.rooks & mask: self.rooks ^= mask - elif piece_type == QUEEN: + piece_type = ROOK + elif self.queens & mask: self.queens ^= mask - elif piece_type == KING: + piece_type = QUEEN + elif self.kings & mask: self.kings ^= mask + piece_type = KING else: return None @@ -1746,6 +1753,12 @@ def from_chess960_pos(cls, scharnagl: int) -> Self: class _BoardState: + __slots__ = ( + "pawns", "knights", "bishops", "rooks", "queens", "kings", + "occupied_w", "occupied_b", "occupied", "promoted", + "turn", "castling_rights", "ep_square", "halfmove_clock", "fullmove_number", + ) + def __init__(self, board: Board) -> None: self.pawns = board.pawns self.knights = board.knights