구성
Pydantic의 동작은 BaseModel.model_config
를 통해 제어할 수 있으며 TypeAdapter
에 대한 인수로 제어할 수 있습니다.
!!! note v2.0 이전에는 Config
클래스가 사용되었습니다. 이는 여전히 지원되지만 더 이상 사용되지 않습니다 .
from pydantic import BaseModel, ConfigDict, ValidationError
class Model(BaseModel):
model_config = ConfigDict(str_max_length=10)
v: str
try:
m = Model(v='x' * 20)
except ValidationError as e:
print(e)
"""
1 validation error for Model
v
String should have at most 10 characters [type=string_too_long, input_value='xxxxxxxxxxxxxxxxxxxx', input_type=str]
"""
또한 모델 클래스 kwargs로 구성 옵션을 지정할 수 있습니다.
from pydantic import BaseModel, ValidationError
class Model(BaseModel, extra='forbid'): # (1)!
a: str
try:
Model(a='spam', b='oh no')
except ValidationError as e:
print(e)
"""
1 validation error for Model
b
Extra inputs are not permitted [type=extra_forbidden, input_value='oh no', input_type=str]
"""
- 자세한 내용은 추가 속성 섹션을 참조하세요.
마찬가지로, Pydantic의 @dataclass
데코레이터를 사용하는 경우:
from datetime import datetime
from pydantic import ConfigDict, ValidationError
from pydantic.dataclasses import dataclass
config = ConfigDict(str_max_length=10, validate_assignment=True)
@dataclass(config=config)
class User:
id: int
name: str = 'John Doe'
signup_ts: datetime = None
user = User(id='42', signup_ts='2032-06-21T12:00')
try:
user.name = 'x' * 20
except ValidationError as e:
print(e)
"""
1 validation error for User
name
String should have at most 10 characters [type=string_too_long, input_value='xxxxxxxxxxxxxxxxxxxx', input_type=str]
"""
표준 라이브러리 또는 TypedDict
의 dataclass
를 사용한 구성¶
표준 라이브러리 또는 TypedDict
의 dataclass
사용하는 경우 대신 __pydantic_config__
사용해야 합니다.
from dataclasses import dataclass
from datetime import datetime
from pydantic import ConfigDict
@dataclass
class User:
__pydantic_config__ = ConfigDict(strict=True)
id: int
name: str = 'John Doe'
signup_ts: datetime = None
또는 with_config
데코레이터를 사용하여 유형 검사기를 준수할 수 있습니다.
from typing_extensions import TypedDict
from pydantic import ConfigDict, with_config
@with_config(ConfigDict(str_to_lower=True))
class Model(TypedDict):
x: str
전역적으로 동작 변경¶
Pydantic의 동작을 전역적으로 변경하려면 구성이 상속되므로 사용자 정의 model_config
사용하여 사용자 정의 BaseModel
생성할 수 있습니다.
from pydantic import BaseModel, ConfigDict
class Parent(BaseModel):
model_config = ConfigDict(extra='allow')
class Model(Parent):
x: str
m = Model(x='foo', y='bar')
print(m.model_dump())
#> {'x': 'foo', 'y': 'bar'}
model_config
Model
클래스에 추가하면 Parent
의 model_config
와 병합 됩니다.
from pydantic import BaseModel, ConfigDict
class Parent(BaseModel):
model_config = ConfigDict(extra='allow')
class Model(Parent):
model_config = ConfigDict(str_to_lower=True) # (1)!
x: str
m = Model(x='FOO', y='bar')
print(m.model_dump())
#> {'x': 'foo', 'y': 'bar'}
print(m.model_config)
#> {'extra': 'allow', 'str_to_lower': True}
本文总阅读量次