Skip to content

Instantly share code, notes, and snippets.

@juanje
Last active February 21, 2023 09:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanje/a6757c7a2af9a9abe1f329dd1a879892 to your computer and use it in GitHub Desktop.
Save juanje/a6757c7a2af9a9abe1f329dd1a879892 to your computer and use it in GitHub Desktop.
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