Python Dataclasses Are Even More AWESOME With: '__post_init__'

preview_player
Показать описание
Today, we will be learning about the hidden power that comes with __post_init__ in Python. This functionality is super nice when you are working with data classes.

▶ Become job-ready with Python:

▶ Follow me on Instagram:

00:00 Intro
00:15 Imports
00:29 Creating a dataclass
01:31 Placeholder
01:55 Using post_init
02:16 Does it work though?
02:56 Yay!
03:31 InitVar
05:51 Mutable fields
07:40 What do you think?
Рекомендации по теме
Комментарии
Автор

Great video. Keep in mind that if the dataclass is frozen, your __post_init__ assignment won't work.

elatedbento
Автор

While the feature can have usage some times, for the actual price attributes, it sould be a @property that is dynamically computed at each call of the attributes
Because it might be that rare or price per kilo or grams change through time

loicquivron
Автор

total_value: float = field(init=False)
what a clear and understandable syntax

sunofabeach
Автор

In the past I wanted to initialize a dataclass from a dictionary. My problem was, that my dataclass contained fields which were dataclasses too. Like this:

@dataclass
class A:
name: str

@dataclass
class B:
a: A

So when I initialized it with data:

my_data = {"a" : {"name": "foo"}}
b = B(**my_data)


The field a in b got type dict instead of A.

The solution was that I wrote this post init

@dataclass
class B:
a: A
def __post_init__(self):
self.a = A(**self.a)


I think this is a pretty common use-case: For example you get some complex object via json in a web application.

I think a great solution could be to add another argument for field, named factory, so I can write this:

@dataclass
class B:
a: A = field(factory=A)

rolandsz
Автор

Thank you for showing us this features!

vanka_feelgood
Автор

This was very informative, thank you. I do have one question: why are you annotating types that can be inferred? I took a pause on Python before types were added and am getting back into it and everyone seems to be doing this. Almost every statically typed language has adopted type inferencing over the past decade to avoid unnecessary boiler-plate while everyone doing this in Python is going in the opposite direction. It looks like the type-checkers and IDE's in Python handle type inferencing so why add the type?

herberttlbd
Автор

you didnt explain why we need "InitVar" and what it does....

robosergTV
Автор

Shouldn't checked prices in Denmark. The same ratio, but twice for each fruit. Mayhaps for the later holidays, anyways greets from Poznań 😃

cybernetic-ransomware
Автор

Bro loves Fruits! Thanks to Fruits, otherwise, we wouldn't be learning all the Python we have done so far.

inkuban
Автор

>2.5 kg apple.
Wtf kind of apples do you have?

johnharmon
Автор

You should almost **never** use init=false fields. Part of the fundamental semantic contract of a dataclass is the idea that the object is a pure product type of its fields, with all of its state able to be immediately reconstituted from a serialized representation of those fields. init=false fields implicitly violate that semantic contract, and while it's possible to add additional logic that can re-rationalize the class's behavior, it's rarely worth it.

AJMansfield
Автор

Okay but if you need to import the `dataclass` decorator, type `field(init=False)` (which most people probably don't know what it does), and then implement an obscure dunder method (that I, and I assume many others, have never seen before), why not just use a normal python class at this point? What benefits are there to using data classes? Not trying to be snarky, just genuinely curious since I haven't really used dataclasses until now.

munzutai
Автор

Isn't this the basic functionality of dataclasses and kind of substitute for __init__? I mean, if you work with data classes, you know about this from the beginning. Why do you present it as "even more awesome"?

Ivan-Bagrintsev
Автор

But you can do the same using __init__ right?

flamendless