Immutable Data Classes
00:00
Immutable data classes. One of the defining features of the namedtuple
you saw earlier is that it’s immutable, i.e. the value of its fields may never change. For many types of data classes, this is a great idea! To make a data class immutable, set frozen=True
when you create it.
00:23
The following is an immutable version of the Position
class you saw earlier on. In a frozen data class, you can’t assign values to the fields after creation.
01:09 One thing to be aware of is that if your data class contains mutable fields, those might still change. This is true for all nested data structures in Python.
01:52
Even though ImmutableCard
and ImmutableDeck
are immutable, the list holding cards
isn’t. You can therefore still change the cards in the deck.
02:39
To avoid this, make sure all fields of an immutable data class use immutable types, but remember that types are not enforced at runtime. The ImmutableDeck
should be implemented using a tuple instead of a list.
02:55 In the next section of the course, you’ll take a look at how to use inheritance with data classes.
Become a Member to join the conversation.