Dataclasses: The code generator to end all code generators - Deepstash

Bite-sized knowledge

to upgrade

your career

Ideas from books, articles & podcasts.

created 6 ideas

I started using Dataclasses and I think you should too

Dataclasses:  The code generator to end all code generators

Dataclasses: The code generator to end all code generators

PyCon 2018

STASHED IN:

108 reads

Dataclasses & What are they for

Dataclasses are an implementation of a code generator, similar to a Named Tuple.

The idea of using a code generator is to save time and reduce wordiness.

There are two views about the purpose of Dataclasses:

  1. It makes a mutable da...

A History Lesson

In the beginning there where:

  • dicts for look-ups
  • tuples for structures
  • hand-written classes for more functionality

Later Named Tuples where added as a code generator with the goal of adding ...

Comparison with Named Tuples

  • Dataclasses are by default mutable
  • Named Tuples have methods which start with an underscore which can be confusing. Ex: obj._replace...

RAYMOND HETTINGER

If you have an immutable mind get out!

  • Dunder methods like init, repr, eq, lt, le, etc.
  • Frozen nature by generating dunder methods for __setattr__ and __delattr__
  • Class variables for the provided attributes

The code generation can be configured by providing keyword a...

A Complex Example of using Dataclasses

In the image example, the generated code includes:

  • typed attributes
  • hidden attributes from __repr__ response
  • custom __hash__ dunder with the selected fields
  • attribute with default factory value in __init__ constructor

5 Reactions

Comment

It's time to

READ

LIKE

A PRO!

Jump-start your

reading habits

, gather your

knowledge

,

remember what you read

and stay ahead of the crowd!

Takes just 5 minutes a day.


TRY THE DEEPSTASH APP

+2M Installs

4.7 App Score