Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Last active February 22, 2019 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokiky/8f0c1ca9afdf3ccd72425f409d31bcd4 to your computer and use it in GitHub Desktop.
Save hirokiky/8f0c1ca9afdf3ccd72425f409d31bcd4 to your computer and use it in GitHub Desktop.
Model (for validators, ORM, form library) by using dataclass
from dataclasses import dataclass, field as dc_field
# Library
def field(default, verbose_name="", help_text=""):
return dc_field(
default=default,
metadata={
'verbose_name': verbose_name,
'help_text': help_text,
}
)
# mypy doen't recognize aliases for dataclass
# So we can't provide nice @model class decorator intead of dataclass
# https://github.com/python/mypy/issues/5383
class Model:
def print_fields(self):
for name, field in self.__dataclass_fields__.items():
print(field.metadata['verbose_name'], getattr(self, name))
# User
@dataclass
class User(Model):
name: str = field("john", "名前", "User name")
user = User(name="hiroki")
user.print_fields() # 名前 hiroki
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment