Pydanticã¯ãPythonã§ãã¼ã¿ã®æ¤è¨¼ï¼ããªãã¼ã·ã§ã³ï¼ãå®è£ ããããã®ã©ã¤ãã©ãªã§ãã
åºæ¬çãªå
¥ååã®æ¤è¨¼ã¯Typingãè¨è¿°ããã ãã§å®è£
ã§ããã¨ãããã¨ã§ãæè¿ã®åãã³ããè¨è¿°ããPythonã³ã¼ãã¨çµã¿åããã¦ä½¿ããã¨ãæ³å®ãã¦ãã¾ãã
docs.pydantic.dev
ä¸æ¹ãPythonã«ã¯æ¨æºã¢ã¸ã¥ã¼ã«ã§ã dataclasses
ã¨ããã®ãããã¾ãã
docs.python.org
dataclassesã¢ã¸ã¥ã¼ã«ã«å«ã¾ããdataclassãã³ã¬ã¼ã¿ã使ãã¨ãåãã³ãã使ã£ã¦ç°¡åã«ãã¼ã¿åãè¨è¿°ã§ãã¾ãã
Pydanticã¯ãã®dataclassã¨äºææ§ã®ããæ©è½ãæä¾ãã¦ããã®ã§ãããã試ãã¦ã¿ã¾ãã
dataclassesã§ã®è¨è¿°
main.py:
from dataclasses import dataclass @dataclass class User: id: int name: str user1 = User(id=123, name="foo") print(user1) user2 = User(id="abc", name="bar") print(user2)
æå³çã« user2.id
ã¯intåã§ã¯ãªãæååãæå®ãã¦ãã¾ããå®è¡çµæã¯ãããªãã¾ãã
$ python main.py User(id=123, name='foo') User(id='abc', name='bar')
æ¨æºã¢ã¸ã¥ã¼ã«ã®dataclassã§ä½æããã¯ã©ã¹ã§ã¯ãç¹ã«ããªãã¼ã·ã§ã³ã®å¦çã¯ãªãã®ã§ãPythonã®ã³ã¼ãã¨ãã¦å®è¡å¯è½ã§ããã°ã¨ã©ã¼ã¯çºçãã¾ããã
ãã ããmypyã§åãã§ãã¯ããã¦ã¿ãã¨ãåã®ä¸æ£ãæ¤åºã§ãã¾ãã
$ mypy main.py main.py:10: error: Argument "id" to "User" has incompatible type "str"; expected "int" [arg-type] Found 1 error in 1 file (checked 1 source file)
pydantic.dataclassesã§ã®è¨è¿°
dataclassãPydanticã®ãã®ã«åãæ¿ãã¦ã¿ã¾ãã importã®ï¼è¡ã ãå¤æ´ãã¾ããã
main.py:
from pydantic.dataclasses import dataclass # ããã ãå¤æ´ @dataclass class User: id: int name: str user1 = User(id=123, name="foo") print(user1) user2 = User(id="abc", name="bar") print(user2)
å®è¡çµæã¯ãããªãã¾ãã
$ python main.py User(id=123, name='foo') Traceback (most recent call last): File "/home/vagrant/tmp/pydantic/main.py", line 10, in <module> user2 = User(id="abc", name="bar") ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vagrant/tmp/pydantic/venv/lib/python3.12/site-packages/pydantic/_internal/_dataclasses.py", line 121, in __init__ s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s) pydantic_core._pydantic_core.ValidationError: 1 validation error for User id Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str] For further information visit https://errors.pydantic.dev/2.10/v/int_parsing
pydanticã®ValidationErrorãçºçãã¾ããã
æ¨æºã¢ã¸ã¥ã¼ã«ã®dataclassesã¨åæ§ã®æ¸ãæ¹ã§ãpydanticãããã«å°å ¥ã§ããã®ã¯èå³æ·±ãã§ãã
pydanticã®ããã¥ã¡ã³ãã«ã¯ãBaseModelãç¶æ¿ããã®ã¨dataclassã使ãã®ã§ã¯ãæ©è½çãªå·®ãããã¨ãæ¸ããã¦ããã®ã§ãå©ç¨ããéã«ã¯æ°ãä»ãã¦ãããã»ããè¯ãããã§ãã