Wednesday, October 22, 2025

The right way to use Python dataclasses

 class Guide:     '''Object for monitoring bodily books in a group.'''     def __init__(self, identify: str, weight: float, shelf_id:int = 0):         self.identify = identify         self.weight = weight # in grams, for calculating delivery         self.shelf_id = shelf_id     def __repr__(self):         return(f"Guide(identify={self.identify!r},             weight={self.weight!r}, shelf_id={self.shelf_id!r})") 

The most important headache right here is that you have to copy every of the arguments handed to __init__ to the article’s properties. This isn’t so dangerous should you’re solely coping with Guide, however what if in case you have extra courses—say, a Bookshelf, Library, Warehouse, and so forth? Plus, typing all that code by hand will increase your possibilities of making a mistake.

Right here’s the identical class applied as a Python dataclass:

 from dataclasses import dataclass @dataclass class Guide:     '''Object for monitoring bodily books in a group.'''     identify: str     weight: float      shelf_id: int = 0 

While you specify properties, referred to as fields, in a dataclass, the @dataclass decorator routinely generates all of the code wanted to initialize them. It additionally preserves the kind info for every property, so should you use a linting too that checks kind info, it can make sure that you’re supplying the correct sorts of variables to the category constructor.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles