Day 7 — Python dataclasses are awesome!
18 August 2020 · recurse-center TweetToday I tried dataclasses for a project (first time!). And I'm sold because I don't have to define an __init__
function anymore, and they automatically generate a repr too. Also, type annotations!
>>> from dataclasses import dataclass
>>>
>>> @dataclass
class Point:
x: int = 0
y: int = 0
z: int = 0
>>>
>>> p = Point(1, 2, 3)
>>> p
Point(x=1, y=2, z=3)
Though I couldn't think of an elegant way to create new attributes (based on existing ones) when an object is instantiated. Maybe the property
decorator is an answer, I'll check out the docs tomorrow! I also want to try attrs after reading this blog post by Glyph Lefkowitz.