Python Dataclasses: Here's 7 Ways It Will Improve Your Code

Python Dataclasses: Here's 7 Ways It Will Improve Your Code

pixegami

6 месяцев назад

6,941 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@pixegami
@pixegami - 23.12.2023 02:41

Here's some additional important details about @datacalsses that a viewer called out (thank you @FrederikSchumacher):
1. Type annotations are not validated or enforced — they can act as a nice guide for you, but be aware that Python won't throw and error or warn you if you use a different type in runtime.
2. Frozen (constant) lists can have items appended/removed (similar to a constant array in Typescript). If you want the list operations itself to be immutable too, try using tuples instead.
3. **kwargs initialisation works on the initial instance of the dataclass, but not on nested dataclasses or fields (there you might want to look at Pydantic instead, which I believe does do that).

Ответить
@FrederikSchumacher
@FrederikSchumacher - 19.12.2023 21:36

Really solid video. I'm really glad the options frozen and order where presented. I wish you had mentioned something potentially confusing about the type annotations: although the type annotations are required for the fields declaration, they're not validated or enforced. Meaning it's possible to declare a field "name: str" but then assign some other type of value. Another gotcha is even when using frozen, this only applies to assignment to the fields, not the values. So something like "tags: list = field(default_factory=list)" still allows modification of the list (eg. using append or extend).
And one more gotcha about the **kwargs initialization: this only applies to the initial instance, not any nested fields using dataclasses - that's related to the aforementioned field types not being "used" internally. This can become potentially confusing and lead to bugs, if one isn't aware of that. So, while dataclasses.asdict works recursive, there's not really an equivalent fromdict and using **kwargs can introduce bugs.

Ответить
@obc9794
@obc9794 - 12.12.2023 22:25

Nice introduction to dataclasses, Thanks

Ответить
@mingjunlim5205
@mingjunlim5205 - 12.12.2023 12:17

Your explanation is awesome, thank you so much!
Now, I wonder could we combine both dataclasses and Pydantic~ HAHAHHAHA

Ответить
@byitkc
@byitkc - 12.12.2023 05:20

Great introduction to dataclasses! I especially appreciated the tip about making dataclasses immutable, something I will definitely use on my future projects. Thank you!

Ответить
@user-ky1fv4ul2c
@user-ky1fv4ul2c - 11.12.2023 19:47

Thank you! Great overview.

Ответить
@Orcrambo
@Orcrambo - 11.12.2023 18:07

Nice video, +1 for Pydantic!

Ответить
@hugo-onzakorderra8851
@hugo-onzakorderra8851 - 11.12.2023 17:46

Nice guide to dataclasses!

Ответить
@xxonoxxtg
@xxonoxxtg - 11.12.2023 17:26

Thank you very much 🤓

Ответить