Skip to content

Commit c9f2ade

Browse files
committed
✨ Add (module): Pydantic introduction module
1 parent c8eecfb commit c9f2ade

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

introduction/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
Package introduction initialization.
3+
"""

introduction/pydantic_intro.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
This module demonstrates an introductory example of using Pydantic for data
3+
validation within a Python application.
4+
It defines a User model with validation on the name attribute to ensure it
5+
contains both a first and last name separated by a space.
6+
"""
7+
8+
from typing import Optional
9+
10+
from pydantic import BaseModel, PositiveInt, ValidationError, field_validator
11+
12+
13+
class User(BaseModel):
14+
"""
15+
Represents a user with a name and optionally an age.
16+
"""
17+
18+
name: str
19+
age: Optional[PositiveInt] = None
20+
21+
@field_validator(
22+
"name",
23+
mode="before",
24+
)
25+
def validate_composed_name(
26+
cls,
27+
v: str,
28+
) -> str:
29+
"""
30+
Ensure the name contains a space, implying both first and last names.
31+
:param v: The name to be validated
32+
:type v: str
33+
:return: The validated name with proper capitalization.
34+
:rtype: str
35+
"""
36+
if "" "" not in v:
37+
raise ValueError("must contain a space")
38+
return v.title()
39+
40+
41+
try:
42+
user: User = User(
43+
name="johndoe",
44+
age="23",
45+
)
46+
print(user.name)
47+
except ValidationError as exc:
48+
print(exc)

0 commit comments

Comments
 (0)