Skip to content

Instantly share code, notes, and snippets.

@shresthakamal
Created February 21, 2024 04:11
Show Gist options
  • Save shresthakamal/96301d821e7bd9af0b7cb77abbdccbcc to your computer and use it in GitHub Desktop.
Save shresthakamal/96301d821e7bd9af0b7cb77abbdccbcc to your computer and use it in GitHub Desktop.
Data Class Guides in Python >=3.10
import random
import string
from dataclasses import dataclass, field
def generate_id() -> str:
return "".join(random.choices(string.ascii_uppercase, k=12))
"""
dataclass:
- Frozen = You cant change the class attributes once it is initialized
- kw_only = You have to mention the attributes in kw=value manner while initializing the class object like Person(name = "A") not Person("A")
- slots : Accessing object's attributes will be very fast
"""
@dataclass(frozen=False, kw_only=True, slots=True)
class Person:
name: str
address: str
# we can also define default variables like "active"
active: bool = True
"""
Creating a default value other than boolean, we need to use
the field function which takes in a `default_factory=func` func as
default factory that generates the deafault value
"""
email_addresses: list[str] = field(default_factory=list)
# here a new list is being generated for each instance of person
# e.g of creating default values
id: str = field(init=True, default_factory=generate_id)
"""
you can also specify that an attribute can not be initialized by user so,
id:str = field(init=False, default_factory = generate_id)
"""
# Printing the class attributes
"""
This was the old way of printing the attributes of a class
With dataclass this is not required
def __str__(self)->str:
return f"{self.name}, {self.address}"
"""
# When you want to create other attributes using the attributes provides / initialized
# We will generate the search string from the name and the address
_search_string: str = field(init=False, repr=False)
"""
Search string is something internal to the class like a private variable so it must be hidden, for that:
1. We add the underscore before the variable
2. We assign repr=False
"""
def __post_init__(self) -> None:
self._search_string = f"{self.name} {self.address}"
if __name__ == "__main__":
person = Person(name="Kamal Shrestha", address="123 Chelsea Street")
"""
Default values can also be sent as an initialized values like
person = Person(name="Kamal Shrestha", address="123 Chelsea Street", active=False)
"""
print(person)
# Person(name='Kamal Shrestha', address='123 Chelsea Street', active=True, email_addresses=[], id='JEVCOBQKFFBJ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment