피단틱¶
.
Pydantic은 Python에서 가장 널리 사용되는 데이터 검증 라이브러리입니다.
빠르고 확장 가능한 Pydantic은 린터/IDE/뇌와 잘 작동합니다. 순수하고 표준적인 Python 3.8+에서 데이터가 어떻게 저장되어야 하는지 정의하세요. Pydantic으로 검증하세요.
!!! 성공 "Pydantic V2로 마이그레이션" Pydantic V1을 사용하시나요? 애플리케이션에서 Pydantic V2로 업그레이드하는 방법에 대한 참고 사항은 마이그레이션 가이드를 참조하세요!
from datetime import datetime
from typing import Tuple
from pydantic import BaseModel
class Delivery(BaseModel):
timestamp: datetime
dimensions: Tuple[int, int]
m = Delivery(timestamp='2020-01-02T03:04:05Z', dimensions=['10', '20'])
print(repr(m.timestamp))
#> datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=TzInfo(UTC))
print(m.dimensions)
#> (10, 20)
Pydantic이라는 이름이 왜 그렇게 지정되었나요?
The name "Pydantic" is a portmanteau of "Py" and "pedantic." The "Py" part indicates that the library is associated with Python, and "pedantic" refers to the library's meticulous approach to data validation and type enforcement.
Combining these elements, "Pydantic" describes our Python library that provides detail-oriented, rigorous data validation.
We’re aware of the irony that Pydantic V1 was not strict in its validation, so if we're being pedantic, "Pydantic" was a misnomer until V2 😉.
왜 Pydantic을 사용하나요?¶
- 유형 힌트 기반 — Pydantic을 사용하면 스키마 유효성 검사 및 직렬화가 유형 주석으로 제어됩니다. 배울 것이 적고, 작성할 코드가 적으며, IDE 및 정적 분석 도구와의 통합이 가능합니다. 자세히 알아보기…
- 속도 — Pydantic의 핵심 검증 로직은 Rust로 작성되었습니다. 결과적으로 Pydantic은 Python을 위한 가장 빠른 데이터 검증 라이브러리 중 하나입니다. 자세히 알아보기…
- JSON 스키마 — Pydantic 모델은 JSON 스키마를 생성할 수 있어 다른 도구와 쉽게 통합할 수 있습니다. 자세히 알아보기…
- Strict 및 Lax 모드 — Pydantic은 strict=True 모드(데이터가 변환되지 않음) 또는 Pydantic이 적절한 경우 데이터를 올바른 유형으로 강제 변환하려고 시도하는 strict=False 모드에서 실행될 수 있습니다. 자세히 알아보기…
- 데이터 클래스, TypedDicts 등 — Pydantic은 데이터 클래스 및 TypedDict를 포함한 많은 표준 라이브러리 유형의 유효성 검사를 지원합니다. 자세히 알아보기…
- 사용자 정의 — Pydantic을 사용하면 사용자 정의 유효성 검사기와 직렬 변환기를 사용하여 데이터 처리 방법을 여러 가지 강력한 방식으로 변경할 수 있습니다. 자세히 알아보기…
- 생태계 — 다음과 같은 매우 인기 있는 라이브러리를 포함하여 PyPI의 약 8,000개 패키지가 Pydantic을 사용합니다. FastAPI, Huggingface, Django Ninja, SQLModel 및 LangChain. 자세히 알아보기…
- Battle tested — Pydantic is downloaded over 70M times/month and is used by all FAANG companies and 20 of the 25 largest companies on NASDAQ. If you're trying to do something with Pydantic, someone else has probably already done it. Learn more…
Installing Pydantic is as simple as: pip install pydantic
Pydantic examples¶
To see Pydantic at work, let's start with a simple example, creating a custom class that inherits from BaseModel
:
from datetime import datetime
from pydantic import BaseModel, PositiveInt
class User(BaseModel):
id: int # (1)!
name: str = 'John Doe' # (2)!
signup_ts: datetime | None # (3)!
tastes: dict[str, PositiveInt] # (4)!
external_data = {
'id': 123,
'signup_ts': '2019-06-01 12:22', # (5)!
'tastes': {
'wine': 9,
b'cheese': 7, # (6)!
'cabbage': '1', # (7)!
},
}
user = User(**external_data) # (8)!
print(user.id) # (9)!
#> 123
print(user.model_dump()) # (10)!
"""
{
'id': 123,
'name': 'John Doe',
'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1},
}
"""
id
is of typeint
; the annotation-only declaration tells Pydantic that this field is required. Strings, bytes, or floats will be coerced to ints if possible; otherwise an exception will be raised.name
is a string; because it has a default, it is not required.signup_ts
is adatetime
field that is required, but the valueNone
may be provided; Pydantic will process either a unix timestamp int (e.g.1496498400
) or a string representing the date and time.tastes
is a dictionary with string keys and positive integer values. ThePositiveInt
type is shorthand forAnnotated[int, annotated_types.Gt(0)]
.- The input here is an ISO8601 formatted datetime, Pydantic will convert it to a
datetime
object. - The key here is
bytes
, but Pydantic will take care of coercing it to a string. - Similarly, Pydantic will coerce the string
'1'
to an integer1
. - Here we create instance of
User
by passing our external data toUser
as keyword arguments - We can access fields as attributes of the model
- We can convert the model to a dictionary with
model_dump()
If validation fails, Pydantic will raise an error with a breakdown of what was wrong:
# continuing the above example...
from pydantic import ValidationError
class User(BaseModel):
id: int
name: str = 'John Doe'
signup_ts: datetime | None
tastes: dict[str, PositiveInt]
external_data = {'id': 'not an int', 'tastes': {}} # (1)!
try:
User(**external_data) # (2)!
except ValidationError as e:
print(e.errors())
"""
[
{
'type': 'int_parsing',
'loc': ('id',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'not an int',
'url': 'https://errors.pydantic.dev/2/v/int_parsing',
},
{
'type': 'missing',
'loc': ('signup_ts',),
'msg': 'Field required',
'input': {'id': 'not an int', 'tastes': {}},
'url': 'https://errors.pydantic.dev/2/v/missing',
},
]
"""
- The input data is wrong here —
id
is not a valid integer, andsignup_ts
is missing User(...)
will raise aValidationError
with a list of errors
Who is using Pydantic?¶
Hundreds of organisations and packages are using Pydantic. Some of the prominent companies and organizations around the world who are using Pydantic include:
For a more comprehensive list of open-source projects using Pydantic see the list of dependents on github, or you can find some awesome projects using Pydantic in awesome-pydantic.
本文总阅读量次