Skip to content

Instantly share code, notes, and snippets.

Last active Apr 19, 2020
What would you like to do?
Example for an User class in Python with dataclasses
from dataclasses import 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.id_to_name(self.user_id)
if not = self.id_to_email(self.user_id)
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
def id_to_email(user_id: str) -> str:
email = user_id + '@' + DOMAIN
return email
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
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