Loading video player…

Basic Data Classes

00:00 Basic data classes. Let’s get back to data classes. As an example, you’ll see a Position class that will represent geographic positions with a name as well as the latitude and longitude.

00:29 What makes this a data class is the @dataclass decorator just above the class definition. Beneath the class Position: line, you simply list the fields you want in your data class.

00:40 The colon (:) notation used for the fields is a feature that was introduced in Python 3.6 called variable annotations. You’ll soon see more about this notation and why we specify data types like str (string) and float. Those few lines of code are all you need.

00:56 The new class is ready for use.

01:25 You can also create data classes in a similar way to named tuples. The following is almost equivalent to the definition of Position you’ve just seen.

01:49 A data class is a regular Python class. The only thing that sets it apart is that it has basic data model methods such as .__init__(), .__repr__(), and .__eq__() implemented for you.

02:03 It’s easy to add default values to the fields of your data class.

02:24 This works exactly as if you had specified the default values in the definition of the .__init__() method of a regular class.

02:46 Later in the course, you’ll learn about default_factory, which gives a way to provide more complicated default values. So far, we have not made a big fuss of the fact that data classes support typing out of the box.

03:00 You’ve probably noticed that we defined a field with a type hint: name: str says that name should be a text string. In fact, adding some kind of type hint is mandatory when defining the fields in your data class. Without a type hint, the field will not be a part of the data class.

03:20 However, if you don’t want to add explicit types to your data class, use Any from the typing module.

03:46 While you need to add type hints in some form when using data classes, these types are not enforced at runtime. The following code runs without any problems.

04:01 This is how typing in Python usually works: Python is and will always be a dynamically typed language. To actually catch type errors, type checkers like Mypy can be run on your source code.

04:16 You already know that a data class is just a regular class. This means you can freely add any methods you want to that class. As an example, let us calculate the distance between one position and another along the Earth’s surface. One way to do this is by using the haversine formula, which is seen onscreen.

04:39 You can add a .distance_to() method to your data class just like you can with normal classes. And here, you’ll see the distance method being added to the Position data class.

06:18 Now that you’ve seen the basics of data classes, in the next section, you’ll see how to make them more flexible.

Become a Member to join the conversation.