paint-brush
A Guide to Using Data Classes in Pythonby@charanjitsingh
780 reads
780 reads

A Guide to Using Data Classes in Python

by Charanjit SinghFebruary 5th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Use python data classes to define returning data types if you're still using lists or dict for compound returns.

Company Mentioned

Mention Thumbnail
featured image - A Guide to Using Data Classes in Python
Charanjit Singh HackerNoon profile picture

How many times do you want to return multiple values or a complex data structure from a python function and you end up using a dictionary or list? For example:

def get_center_of_rectangle(topx, topy, bottomx, bottomy):
    .... Logic Here ...
    return pointx, pointy

// OR

def get_center_of_rectangle(topx, topy, bottomx, bottomy):
    .... Logic Here ...
    return {
        "x": pointx,
        "y": pointy
     }

It works but imagine that you are calling this function in other functions. There are the following downsides of this approach:

1. You need to revise the function signature (https://developer.mozilla.org/en-US/docs/Glossary/Signature/Function).
2. Support of typings(https://docs.python.org/3/library/typing.html) module is limited. We often need this support for autocomplete, static tests, and improved documentation.

In "C" Language, you have structs. With the help of structs, we can define the return data type. You can do the same using classes in python. But you'll need to write a hell lot of code to define a single struct. And it's like using a tank (Class) to dig a small hole (Just defining the data structure).

Example: (C structs vs Python Classes)

struct Person {
  char name[50];
  int citNo;
  float salary;
};

class Person:
    name: str
    citNo: int
    salary: float

# In Code:
p = Person()
p.name = "Charanjit"
p.citNo = 1
p.salary = 0.0001
return p

That's why you are not going to prefer writing 5 lines of code (plus the definition of class) just to return a value so most of the time you end up returning

return {
    "name": "Charanjit"
    "citNo": 1
    "salary": 0.00001
}
# or 

return "Charanjit", 1, 0.0001

Python Data Classes are here to rescue

Documentation: https://docs.python.org/3/library/dataclasses.html
Where did I find this: https://stackoverflow.com/questions/35988/c-like-structures-in-python
Where I am going to use this: To replace

return order, order_action, suggestion
in my code

Usage:

from dataclasses import dataclass


@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0


p = Point(1.5, 2.5)

Or

from dataclasses import dataclass


@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0


p = Point(x=1.5, y=2.5, z=56.5)
return p
# or
return Point(x=1.5, y=2.5, z=56.5)
 

Now your python functions are going to return a specific dataclass' object, not the generic dict, or list.

Benefits:

Documentation++
Autocomplete++
ErrorProneCode--