A Guide to Using Data Classes in Python by@charanjitsingh

A Guide to Using Data Classes in Python

image
Charanjit Singh HackerNoon profile picture

Charanjit Singh

Co-Founder Crove.app and eSahayak.io

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

image

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--

Comments

Signup or Login to Join the Discussion

Tags

Related Stories