Software Bits Newsletter

Share this post
Python dataclasses.
softwarebits.substack.com

Python dataclasses.

Or power of slots in a nice package.

Taras Tsugrii
Oct 30, 2021
Comment
Share

In the previous post

Software Bits Newsletter
Python slots.
Dynamic programming languages are popular when it comes to prototyping thanks to REPL and ease with which most of the things, including class schema, can be changed at runtime. But we all know that everything has a cost and this dynamism is not an exception. For example, for a simple class below…
Read more
7 months ago · 1 like · 2 comments · Taras Tsugrii

we’ve discussed how it’s possible to reduce memory and improve performance using slots. The disadvantage of this approach is a slightly verbose and non-intuitive syntax, which was not big enough to dissuade us from using it. Fortunately, Python 3.7 introduced dataclasses.dataclass decorator, which looks very promising, so let’s give it a shot:

Hm, something looks wrong - looks like it’s still using __dict__ attribute, takes extra memory and comes with lookup performance overhead :(

But after taking a second look at its list of keywords, it seems like there is a slots keyword that sounds exactly like what we are searching for.

And… finally success!

We’ve finally got to the same memory footprint and even slightly faster lookup performance than our manually written slots implementation! And all of this comes in a concise and intuitive package! As such from now on, there is no excuse to not take advantage of slots power!

CommentComment
ShareShare

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

TopNewCommunity

No posts

Ready for more?

© 2022 Taras Tsugrii
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing