Python известен своей элегантностью и удобством синтаксиса, который позволяет писать так называемый «приятный» код. В последних версиях языка появилось два инструмента, нацеленных именно на создание приятных объектных моделей: pydantic и dataclasses. Оба решают похожие задачи валидации и сериализации данных, но делают это немного по-разному. Давайте сравним их подходы, чтобы понять сильные и слабые стороны каждого.

photo.jpg

PYDANTIC VS DATACLASSES: СРАВНЕНИЕ ДЕКЛАРАТИВНОГО И ИМПЕРАТИВНОГО ПОДХОДОВ

Определение моделей
В pydantic модели определяются декларативно, через классы с типизированными атрибутами:

from pydantic import BaseModel

class User(BaseModel):
id: int
name: str
signup_ts: datetime = None

В dataclasses используется более императивный подход через декоратор:

from dataclasses import dataclass

@dataclass
class User:
id: int
name: str
signup_ts: datetime = None

Валидация
Pydantic проверяет типы и ограничения при создании модели:

user = User(id="test", signup_ts="bad date") # ошибка валидации

Dataclasses такой валидацией не обладают:

user = User(id="test", signup_ts="bad date") # ok

Сериализация

Pydantic позволяет с лёгкостью конвертировать объекты в JSON:

user = User(id=123)
json_str = user.json() # {'id': 123, 'name': None ...}

В dataclasses процесс сложнее и требует дополнительных библиотек:

# нужен импорт jsonpickle или другой custom encoder
json_str = jsonpickle.encode(user)

В данном примере pydantic выигрывает в объявлении типов и валидации при меньшей многословности кода. Dataclasses же лучше подходят для простых моделей, где важна скорость написания кода.

Иммутабельность

Pydantic модели по умолчанию неизменяемые (immutable):

user = User(id=1)
user.id = 2 # ошибка!

В то время как dataclass’ы можно менять:

user = User(1)
user.id = 2 # ok

Это может быть как плюсом, так и минусом в зависимости от задачи.

Дополнительная функциональность
У pydantic есть расширенные возможности:

Вложенные модели
Конфигурируемые поля
Управление наследованием
Пример вложенной модели:

class Address(BaseModel):
street: str

class User(BaseModel):
id: int
name: str
address: Address

В dataclasses подобное тоже можно реализовать:

@dataclass
class Address:
street: str

@dataclass
class User:
id: int
name: str
address: Address

Таким образом, pydantic позволяет гибко моделировать сложные структуры данных и иерархии классов.

Выводы
В целом:

Pydantic лучше подходит для: валидации, сериализации, сложных моделей
Dataclasses лучше когда нужна: простота, лёгкость, мутабельность

When you should receive your first task in the field of research paper writing, you want to understand it is a very significant kind of work. There are numerous diverse types of research paper writing that you can pick from.

Some of these sorts of writing include proof based composing, cross-functional composing, and academic writing. All these Читать далее

As soon as I started to write my essay for college, I was impressed at how hard it is. The writing is really a slog, also there are a couple of things that I wish I knew before I started. I am certain that most people have exactly the same questions about how to write an essay as I do. Here are a few suggestions.

One thing that I learned Читать далее

A research paper writer is essentially a two-sided type of job. Not only do staff members need to be very well qualified and experienced writers that could create incredible ideas to life by using their voice, however they need to also be expert researchers who understand where to locate the most reliable sources of data on which to base their Читать далее

Engaged in located at just one using the net gambling hideaway most of as soon as may construct rest thresholds for that customer. Blackjack is merely from considerably typically the a good number of loved online games one of many ample wheels not to mention VIP on line casino competitors generally, envisioned as to the are able to come to be realized by way of a common tactic. Читать далее

Save and Increase Funds http://coastalsportandwellness.com/family-health/kids-pros-announces-fourth-annual-football-camps-in-savannah/ Information In Maplestory

As facts brackets promoting the employ of monoclonal antibody therapy to decrease fatalities and hospitalizations from COVID-19, UPMC and College or university of Pittsburgh Institution of Remedies physician-scientists will be revealing the health and fitness system’s expertise administering the life-saving medication. Читать далее

Boomwin wetten Soccer Betting Tips

Only a several of all on the web sportsbooks recognize Paypal repayment technique but this range is constantly growing. The additional primary principle to come to be informed of is certainly that all proposition wagers practically, unless stated clearly, implement to the complete 90 a few minutes, plus injury time but not extra penalties or period. • To get started another sport, the participant must have to contain once more good tips to think. Читать далее

What is the best advice meant for attractive ladies who prefer to find men or obtain a date? The short response is simple discover other appealing women! What makes other women of all ages attractive to guys can be distinctive for each guy, so it is important to find out what may and will not make a lady attractive. After almost all, no one wishes to date someone who won’t cause them to laugh, make them feel good about being with all of them, or who have something in accordance with them that makes all of them seem «lazy». Here are a few tips on how to go about selecting other attractive women to get dates or perhaps marriage.

A high level00 man who will be looking for a relationship or even just a single night stand, then you need to realize that you may have a big task ahead of you. To draw more attractive women, you have to start by focusing a lesser amount of on your appears, and more in your inner qualities. This may have some effort to understand but will pay off ten fold when you are trying to get a beautiful female to discover you. At the time you focus on different attractive attributes that a woman finds eye-catching, such as your intelligence, closeness, or appeal, then you should come across seeing that very confident, which will right away show up in the human body language, and will be enough to win over any female.

In order to entice attractive females single-handedly, you need to know what will immediately draw a girl to you. When you discover this, your job turns into much simpler. By learning to be charming and self-assured, you will begin to appear a lot more attractive and confident to the woman you meet. This will instantly maximize her appeal to you, also, allow her to think as though the girl with in appreciate. No amount of physical interest alone will ever be a replacement for true mental connection, through learning how to be an excellent communicator and presenter, you will quickly learn how to astound other people and allow yourself http://russainbrides.com/reviews/charm-date to become self-assured in all facets of your life.

What is the best advice meant for attractive ladies who prefer to find men or obtain a date? The short response is simple discover other appealing women! What makes other women of all ages attractive to guys can be distinctive for each guy, so it is important to find out what may and will not make a lady attractive. After almost all, no one wishes to date someone who won’t cause them to laugh, make them feel good about being with all of them, or who have something in accordance with them that makes all of them seem «lazy». Here are a few tips on how to go about selecting other attractive women to get dates or perhaps marriage.

A high level00 man who will be looking for a relationship or even just a single night stand, then you need to realize that you may have a big task ahead of you. To draw more attractive women, you have to start by focusing a lesser amount of on your appears, and more in your inner qualities. This may have some effort to understand but will pay off ten fold when you are trying to get a beautiful female to discover you. At the time you focus on different attractive attributes that a woman finds eye-catching, such as your intelligence, closeness, or appeal, then you should come across seeing that very confident, which will right away show up in the human body language, and will be enough to win over any female.

In order to entice attractive females single-handedly, you need to know what will immediately draw a girl to you. When you discover this, your job turns into much simpler. By learning to be charming and self-assured, you will begin to appear a lot more attractive and confident to the woman you meet. This will instantly maximize her appeal to you, also, allow her to think as though the girl with in appreciate. No amount of physical interest alone will ever be a replacement for true mental connection, through learning how to be an excellent communicator and presenter, you will quickly learn how to astound other people and allow yourself http://russainbrides.com/reviews/charm-date to become self-assured in all facets of your life.

What is the best advice meant for attractive ladies who prefer to find men or obtain a date? The short response is simple discover other appealing women! What makes other women of all ages attractive to guys can be distinctive for each guy, so it is important to find out what may and will not make a lady attractive. After almost all, no one wishes to date someone who won’t cause them to laugh, make them feel good about being with all of them, or who have something in accordance with them that makes all of them seem «lazy». Here are a few tips on how to go about selecting other attractive women to get dates or perhaps marriage.

A high level00 man who will be looking for a relationship or even just a single night stand, then you need to realize that you may have a big task ahead of you. To draw more attractive women, you have to start by focusing a lesser amount of on your appears, and more in your inner qualities. This may have some effort to understand but will pay off ten fold when you are trying to get a beautiful female to discover you. At the time you focus on different attractive attributes that a woman finds eye-catching, such as your intelligence, closeness, or appeal, then you should come across seeing that very confident, which will right away show up in the human body language, and will be enough to win over any female.

In order to entice attractive females single-handedly, you need to know what will immediately draw a girl to you. When you discover this, your job turns into much simpler. By learning to be charming and self-assured, you will begin to appear a lot more attractive and confident to the woman you meet. This will instantly maximize her appeal to you, also, allow her to think as though the girl with in appreciate. No amount of physical interest alone will ever be a replacement for true mental connection, through learning how to be an excellent communicator and presenter, you will quickly learn how to astound other people and allow yourself http://russainbrides.com/reviews/charm-date to become self-assured in all facets of your life.