Cetrez | Blog | Presentation slides | Nordisk Python Community | Meetup event | @ahultner
By Alexander Hultnér at GothPy 17th of May 2018.
A talk about data classes and how you can use them today.
The code we experimented with in the demo is available in demo.py.
What's the requirements for using data classes?
Python 3.6+ (ordered dicts, type annotations) via pip install dataclasses
When can I use data classes without installing the package?
Dataclasses are native in 3.7
What similar patterns are used in older Python versions?
Attrs was a large inspiration for data classes
The misuse of NamedTuples (wouldn't recommend)
@dataclass
class A:
# Required, need to be first; just like in function signatures
a: str
# Optional value, “nullable”
b: Optional[str] = None
# Optional with default value
c: str = "default"
# Executed at startup
d: str = str(datetime.now())
# Executed when creating class instance
e: str = field(default_factory=lambda: f"Created: {datetime.now()}")
>>> A("Required value")
A(a='Required value', b=None, c='default', d='2018-05-24 20:39:19.930841', e='Created: 2018-05-24 20:40:05.762934')