Dataclasses in Python are nice!

isabelcmdcosta

Isabel Costa

Posted on March 14, 2021

Dataclasses in Python are nice!

Couple weeks ago I learned about dataclasses feature in Python. This feature is a nice way to define classes in python. This was introduced in Python 3.7, in particular PEP 557. To use this feature make sure you are running python version 3.7 or above.

Previously, I knew about defining new classes in python using the self.__init__() function. Here's an example of me defining a class Youtuber.

class Youtuber:
    def __init__(self, name: str, categories: list[str]):
        self.name = name
        self.categories = categories
Enter fullscreen mode Exit fullscreen mode

Now we can use less boilerplate code to define classes. There is no need to install a separate python library, this will come with python standard library (as long as it's > 3.7).

Here's how you can define these now:

from dataclasses import dataclass

@dataclass
class Youtuber:
   """Class for defining youtubers."""
   name: str
   categories: list[str]
Enter fullscreen mode Exit fullscreen mode

In this example above, I am importing it first from dataclasses import dataclass and then defining it. I created a class definition and used @dataclass annotation to tell python how it should interpret this class definition.

Then I can create this in python, as I would do it anyway, regardless of using @dataclass:

Youtuber("Chris Stuckmann", ["movie-reviews"])
Enter fullscreen mode Exit fullscreen mode

Here's how you can try this out, using 3 of my favorite youtube channels :)

youtubers = []
youtubers.append(Youtuber("Chris Stuckmann", ["movie-reviews"]))
youtubers.append(Youtuber("Double Toasted", ["movie-reviews"]))
youtubers.append(Youtuber("The Fitness Marshall", ["fitness"]))

for youtuber in youtubers:
    print(f"{youtuber.name}'s categories are: {youtuber.categories}")
Enter fullscreen mode Exit fullscreen mode

Let's put this all together in a file called youtubers.py and run it! You can copy it from this GitHub gist I created. You should get this output:

$ python youtubers.py  
Chris Stuckmann's categories are: ['movie-reviews']
Double Toasted's categories are: ['movie-reviews']
The Fitness Marshall's categories are: ['fitness']
Enter fullscreen mode Exit fullscreen mode

Hope you enjoyed this short article!
You can find me on https://isabelcosta.github.io/

💖 💪 🙅 🚩
isabelcmdcosta
Isabel Costa

Posted on March 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024