Menu

1 / 2

I Built a Dataclass in 25 Lines of Python. Then I Found Three Bugs.

DEV Community·Alexander Mia·6 months ago
#VjW3A9lM
#bug#code#programming#klass#fields
Reading 0:00
15s threshold

Python's @dataclass is great, but it is a decorator. You sprinkle it on, you get __init__ , __eq__ , __hash__ , __repr__ for free. Lovely.

But what if you wanted a function instead? Call it with kwargs, get back a class. No decorator, no class statement, no module-level boilerplate.

Here is one in 25 lines. And here are the three bugs I found while writing this article.

The result first

Klass = Klass ( a = 1 , b = 2 )

# fields become defaults Klass ( a = 3 ). a # 3 Klass (). a # 1 (class-level default) # equality by attribute dict Klass ( a = 3 ) == Klass ( a = 3 ) # True Klass ( a = 2 ) == Klass ( a = 3 ) # False # hashable, usable as dict keys Klass ( a = 4 ) in { Klass ( a = 5 ): 1 } # False Klass () in { Klass (): 1 } # True # strict validation Klass ( g = 3 ) # NameError: Unkown argument g=3

Enter fullscreen mode

Exit fullscreen mode

The whole implementation

def Klass ( ** fields ): fields [ " __data__ " ] = list ( fields .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.