Skip to content

Instantly share code, notes, and snippets.

@juanje
Last active Apr 19, 2020
Embed
What would you like to do?
Example for an User class in Python with dataclasses
from dataclasses import dataclass
DOMAIN = 'example.com'
@dataclass
class User:
user_id: str = None
name: str = None
email: str = None
role: str = 'standard'
def __post_init__(self):
# The param 'user_id' MUST be passed. The rest are optional.
if not self.user_id:
raise ValueError('Parameter user_id is missing')
if not self.name:
self.name = self.id_to_name(self.user_id)
if not self.email:
self.email = self.id_to_email(self.user_id)
@staticmethod
def id_to_name(user_id: str) -> str:
# 1- Split 'user_id' by the . into a list of words ([name, surname])
# 2- Iterate those words and capitalize them ([Name, Surname])
# 3- Join those words into a single string, but separated by 1 space
name = ' '.join(word.title() for word in user_id.split('.'))
return name
@staticmethod
def id_to_email(user_id: str) -> str:
email = user_id + '@' + DOMAIN
return email
@staticmethod
def email_to_id(email: str) -> str:
if '@' not in email:
raise ValueError('The character @ at the parameter email is missing')
user_id = email.split('@')[0]
return user_id
@staticmethod
def from_dict(source: dict):
user = User(**source)
return user
def to_dict(self) -> dict:
return self.__dict__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment