{"id":217,"date":"2026-07-27T09:57:18","date_gmt":"2026-07-27T01:57:18","guid":{"rendered":"https:\/\/yykcj.com\/?p=217"},"modified":"2026-07-27T09:57:18","modified_gmt":"2026-07-27T01:57:18","slug":"python-%e7%b1%bb%e5%9e%8b%e6%b3%a8%e8%a7%a3%e8%bf%9b%e9%98%b6%ef%bc%9a%e4%bb%8e%e5%85%a5%e9%97%a8%e5%88%b0-pydantic","status":"publish","type":"post","link":"https:\/\/yykcj.com\/?p=217","title":{"rendered":"Python \u7c7b\u578b\u6ce8\u89e3\u8fdb\u9636\uff1a\u4ece\u5165\u95e8\u5230 Pydantic"},"content":{"rendered":"<h2>\u4e3a\u4ec0\u4e48\u9700\u8981\u7c7b\u578b\u6ce8\u89e3\uff1f<\/h2>\n<p>Python \u4f5c\u4e3a\u52a8\u6001\u8bed\u8a00\uff0c\u7075\u6d3b\u4f46\u5bb9\u6613\u5728\u8fd0\u884c\u65f6\u66b4\u9732\u7c7b\u578b\u9519\u8bef\u3002\u7c7b\u578b\u6ce8\u89e3\uff08Type Hints\uff09\u81ea Python 3.5 \u5f15\u5165\uff0c\u7ed3\u5408 IDE \u548c\u9759\u6001\u68c0\u67e5\u5de5\u5177\uff08\u5982 mypy\u3001pyright\uff09\uff0c\u80fd\u5728\u7f16\u7801\u9636\u6bb5\u53d1\u73b0\u6f5c\u5728\u95ee\u9898\u3002Pydantic \u66f4\u8fdb\u4e00\u6b65\uff0c\u5229\u7528\u6ce8\u89e3\u5728\u8fd0\u884c\u65f6\u8fdb\u884c\u6570\u636e\u9a8c\u8bc1\u548c\u89e3\u6790\uff0c\u7279\u522b\u9002\u5408 API \u5f00\u53d1\u3001\u914d\u7f6e\u7ba1\u7406\u7b49\u573a\u666f\u3002<\/p>\n<h2>\u57fa\u7840\u56de\u987e\uff1a\u51fd\u6570\u6ce8\u89e3\u4e0e\u53d8\u91cf\u6ce8\u89e3<\/h2>\n<pre><code class=\"language-python\">\n# \u51fd\u6570\u6ce8\u89e3\ndef greet(name: str, age: int = 18) -&gt; str:\n    return f&quot;Hello {name}, you are {age} years old.&quot;\n\n# \u53d8\u91cf\u6ce8\u89e3\nname: str = &quot;Alice&quot;\ncount: int = 10\n<\/code><\/pre>\n<p><strong>\u6ce8\u610f<\/strong>\uff1a\u6ce8\u89e3\u4ec5\u5728\u9759\u6001\u68c0\u67e5\u65f6\u751f\u6548\uff0c\u8fd0\u884c\u65f6\u4e0d\u4f1a\u5f3a\u5236\u7c7b\u578b\u3002<\/p>\n<h2>\u8fdb\u9636\u7528\u6cd5<\/h2>\n<h3>1. \u6cdb\u578b\u4e0e\u5bb9\u5668\u7c7b\u578b<\/h3>\n<pre><code class=\"language-python\">\nfrom typing import List, Dict, Tuple, Optional, Union, Any\n\n# \u5217\u8868\ndef process_items(items: List[int]) -&gt; None:\n    for item in items:\n        print(item)\n\n# \u5b57\u5178\ndef lookup(data: Dict[str, int], key: str) -&gt; Optional[int]:\n    return data.get(key)\n\n# \u53ef\u9009\u7c7b\u578b\ndef parse(value: Optional[str] = None) -&gt; str:\n    return value if value is not None else &quot;default&quot;\n\n# \u8054\u5408\u7c7b\u578b\ndef handle(value: Union[int, float]) -&gt; float:\n    return float(value)\n<\/code><\/pre>\n<h3>2. TypedDict\uff1a\u5b57\u5178\u7ed3\u6784\u5b9a\u4e49<\/h3>\n<pre><code class=\"language-python\">\nfrom typing import TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n    email: str\n\ndef create_person(person: Person) -&gt; None:\n    print(person[&quot;name&quot;])\n\n# \u4f7f\u7528\np: Person = {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30, &quot;email&quot;: &quot;bob@example.com&quot;}\ncreate_person(p)\n<\/code><\/pre>\n<p><strong>\u6ce8\u610f<\/strong>\uff1aTypedDict \u662f\u8fd0\u884c\u65f6\u666e\u901a\u7684 dict\uff0c\u4f46\u9759\u6001\u68c0\u67e5\u4f1a\u6821\u9a8c\u5b57\u6bb5\u3002<\/p>\n<h3>3. Literal\uff1a\u7cbe\u786e\u503c\u7ea6\u675f<\/h3>\n<pre><code class=\"language-python\">\nfrom typing import Literal\n\ndef set_mode(mode: Literal[&quot;auto&quot;, &quot;manual&quot;]) -&gt; str:\n    return f&quot;Mode set to {mode}&quot;\n\nset_mode(&quot;auto&quot;)  # \u6b63\u786e\nset_mode(&quot;semi&quot;)  # mypy \u62a5\u9519\n<\/code><\/pre>\n<h3>4. NewType\uff1a\u521b\u5efa\u65b0\u7c7b\u578b<\/h3>\n<pre><code class=\"language-python\">\nfrom typing import NewType\n\nUserId = NewType(&quot;UserId&quot;, int)\nuser_id: UserId = UserId(123)\n\ndef get_user(uid: UserId) -&gt; str:\n    return f&quot;User {uid}&quot;\n\nget_user(user_id)  # \u6b63\u786e\nget_user(123)      # \u9759\u6001\u68c0\u67e5\u62a5\u9519\uff0c\u4f46\u8fd0\u884c\u65f6\u6b63\u5e38\n<\/code><\/pre>\n<h3>5. Protocol\uff1a\u9e2d\u5b50\u7c7b\u578b<\/h3>\n<pre><code class=\"language-python\">\nfrom typing import Protocol\n\nclass Flyable(Protocol):\n    def fly(self) -&gt; None: ...\n\nclass Bird:\n    def fly(self) -&gt; None:\n        print(&quot;Flying&quot;)\n\ndef let_it_fly(obj: Flyable) -&gt; None:\n    obj.fly()\n\nlet_it_fly(Bird())  # \u6b63\u786e\uff0c\u4e0d\u9700\u8981\u7ee7\u627f\n<\/code><\/pre>\n<h2>Pydantic\uff1a\u8fd0\u884c\u65f6\u9a8c\u8bc1<\/h2>\n<p>Pydantic \u5229\u7528\u7c7b\u578b\u6ce8\u89e3\u5728\u8fd0\u884c\u65f6\u8fdb\u884c\u6570\u636e\u9a8c\u8bc1\u548c\u5e8f\u5217\u5316\uff0c\u7279\u522b\u9002\u5408\u5904\u7406 JSON \u8f93\u5165\u3002<\/p>\n<h3>\u5b89\u88c5<\/h3>\n<pre><code class=\"language-bash\">\npip install pydantic\n<\/code><\/pre>\n<h3>\u57fa\u7840\u6a21\u578b<\/h3>\n<pre><code class=\"language-python\">\nfrom pydantic import BaseModel, Field, ValidationError\n\nclass User(BaseModel):\n    id: int\n    name: str = Field(..., min_length=1, max_length=50)\n    age: int = Field(..., ge=0, le=150)\n    email: str | None = None\n\n# \u6709\u6548\u6570\u636e\ntry:\n    user = User(id=1, name=&quot;Alice&quot;, age=30, email=&quot;alice@example.com&quot;)\n    print(user.model_dump())  # {&#x27;id&#x27;: 1, &#x27;name&#x27;: &#x27;Alice&#x27;, &#x27;age&#x27;: 30, &#x27;email&#x27;: &#x27;alice@example.com&#x27;}\nexcept ValidationError as e:\n    print(e)\n\n# \u65e0\u6548\u6570\u636e\ntry:\n    User(id=&quot;abc&quot;, name=&quot;&quot;, age=200)\nexcept ValidationError as e:\n    print(e.errors())\n    # [{&#x27;type&#x27;: &#x27;int_parsing&#x27;, ...}, {&#x27;type&#x27;: &#x27;string_too_short&#x27;, ...}, {&#x27;type&#x27;: &#x27;greater_than_equal&#x27;, ...}]\n<\/code><\/pre>\n<p><strong>\u63d0\u793a<\/strong>\uff1aPydantic \u4f1a\u81ea\u52a8\u8fdb\u884c\u7c7b\u578b\u8f6c\u6362\uff08\u5982\u5b57\u7b26\u4e32\u8f6c\u6570\u5b57\uff09\uff0c\u4f46\u4e25\u683c\u6a21\u5f0f\u53ef\u7981\u7528\u3002<\/p>\n<h3>\u9ad8\u7ea7\u9a8c\u8bc1\uff1a\u81ea\u5b9a\u4e49\u9a8c\u8bc1\u5668<\/h3>\n<pre><code class=\"language-python\">\nfrom pydantic import BaseModel, field_validator\n\nclass PasswordModel(BaseModel):\n    password: str\n    confirm_password: str\n\n    @field_validator(&quot;confirm_password&quot;)\n    @classmethod\n    def passwords_match(cls, v, info):\n        if &quot;password&quot; in info.data and v != info.data[&quot;password&quot;]:\n            raise ValueError(&quot;passwords do not match&quot;)\n        return v\n<\/code><\/pre>\n<h3>\u5d4c\u5957\u6a21\u578b\u4e0e\u590d\u6742\u7c7b\u578b<\/h3>\n<pre><code class=\"language-python\">\nfrom pydantic import BaseModel\nfrom typing import List, Optional\n\nclass Address(BaseModel):\n    street: str\n    city: str\n    zip_code: str\n\nclass Company(BaseModel):\n    name: str\n    address: Address\n    employees: List[User]\n\n# \u4ece JSON \u89e3\u6790\ndata = {\n    &quot;name&quot;: &quot;Tech Corp&quot;,\n    &quot;address&quot;: {&quot;street&quot;: &quot;123 Main St&quot;, &quot;city&quot;: &quot;NYC&quot;, &quot;zip_code&quot;: &quot;10001&quot;},\n    &quot;employees&quot;: [\n        {&quot;id&quot;: 1, &quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30},\n        {&quot;id&quot;: 2, &quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 25}\n    ]\n}\ncompany = Company(**data)\nprint(company.model_dump_json(indent=2))\n<\/code><\/pre>\n<h3>\u914d\u7f6e\u4e0e\u6027\u80fd<\/h3>\n<pre><code class=\"language-python\">\nfrom pydantic import BaseModel, ConfigDict\n\nclass FastModel(BaseModel):\n    model_config = ConfigDict(extra=&quot;forbid&quot;, frozen=True)\n    name: str\n\n# extra=&quot;forbid&quot; \u7981\u6b62\u989d\u5916\u5b57\u6bb5\n# frozen=True \u4f7f\u5b9e\u4f8b\u4e0d\u53ef\u53d8\n<\/code><\/pre>\n<h2>\u5b9e\u6218\uff1aAPI \u6570\u636e\u9a8c\u8bc1<\/h2>\n<p>\u7ed3\u5408 FastAPI \u4f7f\u7528 Pydantic \u6a21\u578b\u4f5c\u4e3a\u8bf7\u6c42\u4f53\u9a8c\u8bc1\uff1a<\/p>\n<pre><code class=\"language-python\">\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI()\n\nclass Item(BaseModel):\n    name: str = Field(..., min_length=1)\n    price: float = Field(..., gt=0)\n    is_offer: bool = False\n\n@app.post(&quot;\/items\/&quot;)\nasync def create_item(item: Item):\n    return {&quot;message&quot;: f&quot;Item {item.name} created&quot;, &quot;price&quot;: item.price}\n\n# \u542f\u52a8\uff1auvicorn main:app --reload\n<\/code><\/pre>\n<h2>\u8e29\u5751\u7ecf\u9a8c<\/h2>\n<ol>\n<li><strong>\u8fd0\u884c\u65f6\u7c7b\u578b\u68c0\u67e5<\/strong>\uff1a\u7c7b\u578b\u6ce8\u89e3\u9ed8\u8ba4\u4e0d\u68c0\u67e5\u8fd0\u884c\u65f6\uff0c\u9700\u7528 Pydantic \u6216 <code>typeguard<\/code> \u5e93\u3002<\/li>\n<li><strong>Optional \u4e0e\u9ed8\u8ba4\u503c<\/strong>\uff1a<code>Optional[str]<\/code> \u7b49\u4ef7\u4e8e <code>Union[str, None]<\/code>\uff0c\u4f46\u9ed8\u8ba4\u503c\u9700\u663e\u5f0f\u5199 <code>None<\/code>\u3002<\/li>\n<li><strong>Pydantic V2 \u53d8\u5316<\/strong>\uff1aV2 \u4f7f\u7528 <code>model<em>dump()<\/code> \u66ff\u4ee3 <code>dict()<\/code>\uff0c<code>model<\/em>validate()<\/code> \u66ff\u4ee3 <code>parse_obj()<\/code>\u3002<\/li>\n<li><strong>\u6027\u80fd\u8003\u8651<\/strong>\uff1aPydantic \u9a8c\u8bc1\u6709\u5f00\u9500\uff0c\u5bf9\u9ad8\u6027\u80fd\u573a\u666f\u53ef\u4f7f\u7528 <code>@pydantic.dataclass<\/code> \u6216\u8df3\u8fc7\u9a8c\u8bc1\u3002<\/li>\n<\/ol>\n<h2>\u603b\u7ed3<\/h2>\n<p>\u672c\u6587\u4ece\u57fa\u7840\u7c7b\u578b\u6ce8\u89e3\u5230 Pydantic \u5b9e\u6218\uff0c\u6db5\u76d6\u4e86 Python \u7c7b\u578b\u7cfb\u7edf\u7684\u6838\u5fc3\u8fdb\u9636\u7528\u6cd5\u3002\u7c7b\u578b\u6ce8\u89e3\u4e0d\u4ec5\u63d0\u5347\u4ee3\u7801\u53ef\u8bfb\u6027\uff0c\u8fd8\u80fd\u901a\u8fc7\u9759\u6001\u68c0\u67e5\u51cf\u5c11\u9519\u8bef\uff0c\u800c Pydantic \u5219\u5c06\u5176\u6269\u5c55\u5230\u8fd0\u884c\u65f6\uff0c\u5b9e\u73b0\u6570\u636e\u9a8c\u8bc1\u3001\u5e8f\u5217\u5316\u548c\u914d\u7f6e\u7ba1\u7406\u3002\u4e0b\u4e00\u6b65\u53ef\u4ee5\u63a2\u7d22 mypy \u914d\u7f6e\u3001Pydantic \u7684 <code>Field<\/code> \u51fd\u6570\u9ad8\u7ea7\u9009\u9879\uff0c\u4ee5\u53ca\u5982\u4f55\u7ed3\u5408 <code>dataclasses<\/code> \u4f7f\u7528\u3002<\/p>\n<h2>\u5ef6\u4f38\u9605\u8bfb<\/h2>\n<ul>\n<li><a href=\"https:\/\/docs.pydantic.dev\/\">Pydantic \u5b98\u65b9\u6587\u6863<\/a><\/li>\n<li><a href=\"https:\/\/mypy.readthedocs.io\/\">mypy \u5b98\u65b9\u6587\u6863<\/a><\/li>\n<li><a href=\"https:\/\/docs.python.org\/3\/library\/typing.html\">Python typing \u6a21\u5757\u6587\u6863<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\u672c\u6587\u4ece\u57fa\u7840\u7c7b\u578b\u6ce8\u89e3\u8bb2\u8d77\uff0c\u6df1\u5165\u63a2\u8ba8\u6cdb\u578b\u3001TypedDict\u3001Literal\u7b49\u9ad8\u7ea7\u7528\u6cd5\uff0c\u5e76\u8be6\u7ec6\u4ecb\u7ecdPydantic\u5e93\u5982\u4f55\u5229\u7528\u7c7b\u578b\u6ce8\u89e3\u5b9e\u73b0\u6570\u636e\u9a8c\u8bc1\u4e0e\u5e8f\u5217\u5316\uff0c\u52a9\u4f60\u5199\u51fa\u66f4\u5065\u58ee\u7684Python\u4ee3\u7801\u3002<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[160,86,99,159,161],"class_list":["post-217","post","type-post","status-publish","format-standard","hentry","category-4","tag-pydantic","tag-python","tag-99","tag-159","tag-161"],"_links":{"self":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts\/217","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=217"}],"version-history":[{"count":0,"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts\/217\/revisions"}],"wp:attachment":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=217"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=217"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=217"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}