Introduction
If you write class definitions and then proceed to write their getters, setters, string representations and generate hundreds of lines of code, this post is for you.
One Weird Trick to Reduce Your Code Size
dataclasses
was introduced in Python3.8. You can also look at the (official documentation)[https://docs.python.org/3/library/dataclasses.html]. dataclasses decorator gets you the getters and setters and the __repr__
methods for free. In addition, it also generates equality and comparison operations in case you need to order them. And finally, it also generates the __hash__
method so that we can also use them in case we need to store them in kv datastructures.
How to use it?
Let us define our class this way –
|
|
Different Ways of Creating an Object
|
|
Instantiation using Dictionaries
|
|
Instantiating from Another Object
|
|
Something Similar in C++
Designated Initializers in C++20
Please read this documentation on designated initializers
in C++20. And let us create something similar in C++ as well.
Let us define our struct like this -
|
|
The simplest way of using it is -
|
|
Note that parameters have to be supplied in the same order as specified in the struct. Look at the two definitions for the instances. It is clear that mas1
is more descriptive than meh
. It is descriptive but we can also skip the names using elison
|
|
What if the struct is nested?
If our struct is defined this way –
|
|
We can instantiate our objects in these ways –
|
|
Conclusion
dataclasses
are decorators and need to be added in the python code above the class definition to use them. It’s not a standard python feature. They help us get rid of writing boilerplate code. One can take it a step further and define them using dictionaries. Similarly, we can get the dictionary representatio of the class. I can already imagine this to be very useful when parsing json files.
designated initializers
is part of C++20 and you’ll have to pass the appropriate args in your compiler to enable C++20 features. Their usage is like a dial. You can get extremely descriptive code when turned all the way to the left. Turn the dial all the way to the right and you can define instances using a very flat (albeit confusing) set of values inside braces.
Thanks for reading this post!