If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
Why Stack Overflow recommends it
Stack Overflow users link it when answering questions about dataclass features like sort_index and when recommending dataclasses to people modelling data in plain classes or dicts.
Recommended by 2 people across 2 different months, 2021 to 2021.
What it is
A roughly 11-minute tutorial by ArjanCodes on Python's dataclasses module. It walks through one example covering dataclass creation, sorting and comparing with a sort_index field, default values, frozen read-only objects, and string representation.
What people said
Recommends Shivnaren · 2021-09 · Stack Overflow · on “What is the purpose of sort_index of a Dataclass in Python?”
Setting a sort_index attribute (or indeed, any identifier—the name is irrelevant) in the __post_init__ method appears to be the value on which comparisons are performed. There is an implicit setting of the comparison methods ( __lt__ , __gt__ , etc--read about dunder methods if unfamiliar), using the attributes provided in the __post_init__ method first, and if required, the remaining attributes for resolution. Class constructor from dataclasses import dataclass, field @dataclass(order=True) class Person: sort_index: int = field(init=False) age: int def __post_init__(self): self.sort_index = self.age first example —attribute age is equal: >>> p1 = Person(age=10) >>> p2 = Person(age=10) >>> p
Recommends Joschua · 2021-10 · Stack Overflow · on “Accessing a dictionary as attributes of a custom class”
You are welcome! It answers your question, but I'm not sure if it's the best way to go, as I don't really know your usecase, i.e. if you are building these dicts yourself or getting them as input etc. So in general, if you have full control over the code and data I would also use dataclasses (as recommended below [LINK] but without using the Wizard and just create the instances yourself). If you haven't heard about dataclasses, I can recommend this youtube channel: [this video]
Cites RSale · 2021-12 · Stack Overflow · on “Adding variables to dataclass from json config file”
After watching ArjanCodes [this video] video on dataclasses, I've been trying to add variables to a python dataclass from a json config file to format the font style of a print function printT in Jupyterlab. I use ANSI escapes for the formatting which doesn't work anymore if I import the variables to the dataclass. Instead of formatting the text, the ANSI code get's printed out. # config.json { "lb" : "\n", "solid_line" : "'___'*20 + config.lb", "dotted_line" : "'---'*20 + config.lb", "BOLD" : "\\033[1m", "END" : "\\033[0m" } # config.py from dataclasses import dataclass import json @dataclass class PrintConfig: lb : str solid_line : str dotted_line : str BOLD : str END : str def read_config(conf