Extending the YAML representation

Sometimes, one of our classes has a tidy representation that is nicer than the default YAML dump of attribute values. For example, the default YAML for our Blackjack Card class definitions will include several derived values that we don't really need to preserve.

The yaml module includes a provision for adding a representer and constructor to a class definition. The representer is used to create a YAML representation, including a tag and value. The constructor is used to build a Python object from the given value. Here's yet another Card class hierarchy:

from enum import Enumclass Suit(str, Enum):    Clubs = "♣"    Diamonds = "♦"    Hearts = "♥"    Spades = "♠"class Card:    def __init__(self, rank: str, suit: Suit,  hard: ...

Get Mastering Object-Oriented Python - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.