Alternatives to Standard Classes
00:30 This does work, but it puts a lot of responsibility on you as a programmer. You need to remember that the queen of hearts variable represents a card. For the tuple version, you need to remember the order of attributes.
('Spades', 'A') will mess up your program but probably not give you an easily understandable error message. If you use the
dict version, you must make sure the names of the attributes are consistent.
The example shown onscreen would not work as expected. Furthermore, using these structures is not ideal. The tuple does not give us named access, and the
dict version doesn’t give named attribute lookup.
A better alternative is the
namedtuple. It’s long been used to create readable small data structures, and you can, in fact, recreate the data class example already seen using a
namedtuple as seen onscreen.
So why even bother with data classes? First of all, data classes come with many more features than you’ve seen already. At the same time, the
namedtuple has some other features that are not necessarily desirable.
By design, a
namedtuple is a regular
tuple, which can be illustrated by this comparison seen onscreen. While this might seem like a good thing, this lack of awareness about its own type can lead to subtle and hard-to-find bugs, especially since it will happily compare two different
namedtuple is also by nature immutable. That is, the value of a
namedtuple can never change. In some applications, this is an awesome feature, but in other settings, it would be nice to have more flexibility.
Data classes will not replace all uses of
namedtuple. For instance, if you need your data structure to behave like a tuple, then a
namedtuple is a great alternative! Another alternative, and one of the inspirations for data classes, is the
attrs project does support some features that data classes do not, including converters and validators. Furthermore,
attrs has been around for a while and is supported in older versions of Python.
attrs isn’t part of the standard library, and as such, it would add an external dependency to your projects. If you use data classes, similar functionality will be available everywhere without external dependencies.
In addition to
attrs, there are other similar projects, including
fields. While data classes are a great feature, there are still use cases where one of the older variants fits better.
06:06 For instance, if you need compatibility with a specific API expecting tuples or need functionality not supported in data classes. Now that you’ve seen what the alternatives may be, in the next chapter, you’ll get back to implementing data classes, starting with a simple example.
Become a Member to join the conversation.