osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Should nested classes in an Enum be Enum members?


On 29/06/2018 09:01, Ian Kelly wrote:
> On Thu, Jun 28, 2018 at 10:06 PM Ben Finney <ben+python at benfinney.id.au> wrote:

> @total_ordering
> class ChessPiece(Enum):
>      PAWN = 1, 'P'
>      KNIGHT = 2, 'N'
>      BISHOP = 3, 'B'
>      ROOK = 4, 'R'
>      # ...
> 
>      @property
>      def label(self):
>          return self.value[1]
> 
>      def __lt__(self, other):
>          assert isinstance(other, ChessPiece)
>          return self.value < other.value
> 
> This enum type defines its own ordering based on the relative values
> of the chess pieces.

> class ChessPiece(Enum):
>      PAWN = 'P', pawn_moves, pawn_attacks
>      KNIGHT = 'N', knight_moves, knight_attacks
>      BISHOP = 'B', bishop_moves, bishop_attacks
>      ROOK = 'R', rook_moves, rook_attacks
>      # ...
> 
>      def moves(self, board, from_square):
>          return self.value[1](board, from_square)
> 
>      def attacks(self, board, from_square):
>          return self.value[2](board, from_square)
> 
> Now, elsewhere we can easily do something like:
> 
>      all_moves = []
>      for square in board:
>          piece = board[square]
>          if piece:
>              all_moves.extend(piece.moves(board, square))
> 
> Et voila. ChessPiece is still an enum as it should be, and it also has
> a useful API on top of that.
I get the feeling is that the enum (PAWN, BISHOP etc) is a property of a 
piece, rather than being the cornerstone of everything you might think 
of doing with a chess-piece.

That thinking keeps the that property as a simple type, a simple enum of 
six distinct values with nothing else piled on top to complicate 
matters. And it means the same enum can be used in other contexts 
associated with chess where that other data may be irrelevant.

-- 
bart