|
| 1 | +# ! pip install pydantic |
1 | 2 |
|
| 3 | +from pydantic import BaseModel |
| 4 | + |
| 5 | +class User(BaseModel): |
| 6 | + name: str |
| 7 | + age: int |
| 8 | + email: str |
| 9 | +# Create a user |
| 10 | +user = User( name="Alice", age="25", email="[email protected]") |
| 11 | +print(user.age) |
| 12 | +print(type(user.age)) |
| 13 | + |
| 14 | +from pydantic import BaseModel, Field |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +class Product(BaseModel): |
| 18 | + name: str |
| 19 | + price: float |
| 20 | + description: Optional[str] = None |
| 21 | + in_stock: bool = True |
| 22 | + category: str = Field(default="general", min_length=1) |
| 23 | + |
| 24 | +# All these work |
| 25 | +product1 = Product(name="Widget", price=9.99) |
| 26 | +product2 = Product(name="Gadget", price=15.50, description="Useful tool") |
| 27 | + |
| 28 | +from pydantic import BaseModel, field_validator |
| 29 | +import re |
| 30 | + |
| 31 | +class Account(BaseModel): |
| 32 | + username: str |
| 33 | + email: str |
| 34 | + password: str |
| 35 | + |
| 36 | + @field_validator('username') |
| 37 | + def validate_username(cls, v): |
| 38 | + if len(v) < 3: |
| 39 | + raise ValueError('Username must be at least 3 characters') |
| 40 | + if not v.isalnum(): |
| 41 | + raise ValueError('Username must be alphanumeric') |
| 42 | + return v.lower() # Normalize to lowercase |
| 43 | + |
| 44 | + @field_validator('email') |
| 45 | + def validate_email(cls, v): |
| 46 | + pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' |
| 47 | + if not re.match(pattern, v): |
| 48 | + raise ValueError('Invalid email format') |
| 49 | + return v |
| 50 | + |
| 51 | + @field_validator('password') |
| 52 | + def validate_password(cls, v): |
| 53 | + if len(v) < 8: |
| 54 | + raise ValueError('Password must be at least 8 characters') |
| 55 | + return v |
| 56 | + |
| 57 | +account = Account( |
| 58 | + username="JohnDoe123", |
| 59 | + |
| 60 | + password="secretpass123" |
| 61 | +) |
0 commit comments