Easier Classes: Python Classes Without All The Cruft

By Trey Hunner

Elevator Pitch

Creating well-behaved Python classes shouldn’t require boilerplate. In this talk we’ll see how to easily make classes with proper string representations, comparability, iterability, and immutability.

Description

When bundling up data, sometimes tuples and dictionaries don’t quite cut it. Python’s classes are powerful tools for data storage and manipulation, but it can take quite a bit of boilerplate code to make a well-behaved Python class. In this talk we’re going to discuss how a well-behaved class should work and take a look at a number of helper libraries for creating well-behaved classes.

We’ll first see how to make classes with proper string representations, comparability, iterability, and immutability. Then we’ll dive into helper tools built-in to the standard library and available in third-party libraries.

We’ll look at namedtuple, NamedTuple (not a typo), attrs, and the new Python 3.7 dataclasses.

Most of the libraries discussed in this talk are only available in Python 3, so if you’re not using Python 3, hopefully this talk will encourage you to upgrade.

Notes

This talk is aimed at Python developers who write a lot of small data-holding classes. Audience members are expected to know how classes work in Python. Knowledge of dunder methods and operator overloading would be helpful to understanding but is not essential to appreciating this talk.

Audience members will walk out of this talk inspired to remove many lines of repetitive boilerplate code from their classes by embracing one of the tools discussed during this talk.

I do on-site corporate training for Python and Django teams as my day job. I also teach Python in free webcasts every week and I mentor folks at my local Python study group on a weekly basis.

I spoke at 8 Python and Django conferences in 2016 and 2017. This talk is a new one and I am hoping it will be well-received because Python 2 is very close to on its way out and Python 3 is improving greatly in each new release.

I teach my students about namedtuples and creating Pythonic classes quite frequently and I’m very excited about the possibilities that dataclasses opens up for Python teachers.