惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Project Zero
Project Zero
Security Archives - TechRepublic
Security Archives - TechRepublic
C
Cyber Attacks, Cyber Crime and Cyber Security
Security Latest
Security Latest
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
C
CERT Recently Published Vulnerability Notes
S
Schneier on Security
G
GRAHAM CLULEY
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
F
Full Disclosure
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
Hacker News: Ask HN
Hacker News: Ask HN
G
Google Developers Blog
H
Heimdal Security Blog
O
OpenAI News
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LangChain Blog
C
Cisco Blogs
云风的 BLOG
云风的 BLOG
IT之家
IT之家
Cyberwarzone
Cyberwarzone
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Know Your Adversary
Know Your Adversary
博客园 - 聂微东
The Cloudflare Blog
C
Check Point Blog
K
Kaspersky official blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
月光博客
月光博客
T
Tor Project blog
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
P
Proofpoint News Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
A
About on SuperTechFans
小众软件
小众软件
Cloudbric
Cloudbric
A
Arctic Wolf

Artificial Intelligence in Plain English - Medium

OpenAI launched GPT-5.5 - it’s the death of digital hand-holding The Future of Agentic AI is Not One Genius Model, it is a Team How AI Development Optimizes Smart Parking Management Systems The FAST Framework: A Practical Responsible AI Checklist for Data Scientists Why is Cloud Migration Consulting Important for Businesses? My Team Caught Me Using AI to Merge PRs. The Code Was Fine. The Trust Wasn’t. SQL Tricks Every Data Scientist Should Know I Stopped Chasing AI Hype and Started Building Systems That Actually Worked GPT-5.5: The Model That Thinks Ahead Mastering AI Storytelling: Crafting Prompts for Captivating Narratives Why So Many Businesses Are Switching to Clawdbot for AI Automation The Growing Dependence on AI Tools — And Why It’s Risky How to Cut Claude Code Costs by At least 2 to 3x How The Google Antigravity Agent Hallucinated NSFW Adult Websites? “Vercel Hack Exposed: How a Simple AI Tool Led to a $2M Data Breach” The Vercel Hack: How One AI Tool Cracked Open the Internet’s Deployment Stack AI Chatbot Development Services for Enterprise Data-Sensitive Processes What AI Agent Developers Should Consider When Designing Agents for High-volume Environments My ChatGPT Responds Better Than Yours, Here is the 3-Step Guide How To Create A Custom AI Chatbot, Train & Deploy It In 48 Hrs Learning in the Age of Intelligent Systems: Why Human Understanding Still Matters Everyone Is Learning AI, So Why Will Most Still Fail? AI Is Learning Faster Than You Think What If Your Next Best Friend Is a Robot That Even Feels Real? OpenAI Quietly Broke the Way You Build AI Apps The AI Superpower Standoff: Why the OpenAI vs. Anthropic War Looks Exactly Like the US vs. Iran The LLM Tools That Actually Matter in Production (Not LangChain, Not the OpenAI SDK) The Most Dangerous Use of Artificial Intelligence Yet! | AI Porn Why Your AI Chatbot Gives Vague Answers (And Why That Should Matter to You) How Do You Prove You’re You, After AI Has Evolved? AWS Bedrock Agents Keep Crashing Mid-Flow, Here’s Why and How to Actually Fix It I Built a Full Stack App Without Writing Code (AI vs Developer Reality Check) Why Your Business Doesn’t Need a Chatbot — It Needs an AI Agent 3 Counter-Intuitive Things I Learned Promoting my Micro-SaaS I Tested 5 LLMs Across 100 Real-World Tasks — The Winner Isn’t Who You Think Why Claude Design is Terrifying UX Teams? 9 AI Behaviors That Developers Misinterpret Completely How Large Language Models Actually Work (Explained Simply) The 4-Month Blueprint: How to Become an AI Automation Builder Claude Opus 4.7: The Model That Verifies Itself The $1 AI Stack: Build Scalable AI Systems Without Burning Cash How Blockchain Development Solutions Enable Decentralized Innovation Your AI Is Lying to You — And Your Tests Are Helping It How to Create a Local AI Assistant Using Python Without Paying for APIs What Is a Context Graph — and Why Is Everyone Talking About It? Jobs Are Disappearing. Careers Are Breaking. The Smartest People Are Building This Instead The Silent Trade: Convenience in Exchange for Control Why “The Dark Knight” and “The Avengers” Are 78% Similar, A Math-First Guide to Movie… Claude Skills — The Workflows That Actually Stick Claude Code’s source code just leaked. Today I’m going to teach you how it works. Build a Production-Grade AI Invoice Processing Pipeline in Snowflake — Using Only SQL The AI-Driven Developer Blueprint: How Modern Software Really Works The Truth About AI — From First Model to Real-World Systems AI in Everyday Life Google’s Gemma 4 Is Beating Models 20x Its Size And You Can Run It on Your Laptop 8 AI Scenarios Where You Should Never Trust the Output How to Make Money from Podcast Videos with AI: A Complete 4-Step Workflow for Creators (2026 Guide) n8n Google Search Workflow Automation: Streamlined SEO Indexing with Google APIs Why Drug Discovery Gets the Wrong Targets — and How Causal AI Can Fix It Why Your Workflow Is Broken (And How AI Automation Fixes It) Failure Mode and Effects Analysis (FMEA): Turning Risk into Preventive Control Measurement System Analysis (MSA): Why Good Projects Fail Without Good Data Advanced DMAIC Tools: Moving Beyond the Basics in Lean Six Sigma AI Won’t Fix a Messy Operation The Invisible Tech Revolution That’s Already Reshaping Your Job (And No, You Don’t Need to Know How… The Battle of the Bastards Is Happening Right Now. And Your Job Is Jon Snow. 7 Real-World Machine Learning Projects You Can Build in a Weekend 5 Prompting Habits That Are Destroying Your AI’s Logic MiniMax M2.7: The Model That Helped Build Itself The Token Dependency: Why Cloud-Only AI is a Single Point of Failure One Agent, Many Skills: Why You Don’t Always Need a Multi-Agent Architecture AI, Machine Learning, and Data Science in Action The Human-AI Symbiosis in Data Science Insurance Chatbots: Benefits, Use Cases & Examples The AI Model Anthropic Won’t Let You Use From Idea to Production: Our Approach to Deep Learning Development From 50 Files to One Graph: How Graphify Turns Code Into Knowledge Meta Just Hit Reset on Its AI Strategy And Muse Spark Is the First Big Sign The Complete Suno AI Prompt & Style Collection for Viral Music (2026) CLAUDE.md — The File Claude Reads Before You Speak Stop Chatting with Claude Code. Start Building on It. AI Agents: The Only Guide You’ll Ever Need (And Why Your Job Depends On It) The Stencil Strategy: How to Automate World-Class Medium Content Solving ‘AI Amnesia’ Through Compounding Strategy I Let AI Do My Job for 30 Days — These Were the Things It Couldn’t Do I Take My AI Agent Everywhere With Claude Dispatch: 3 Use Cases You Must Know AI Is Writing My Code — So What Exactly Is My Job Now? NVIDIA Releases AITune: The Toolkit That Automatically Finds the Fastest Inference Backend for Any… How AI Creates Business Value: The 5 Core Types of AI Enterprise AI Architecture Cheatsheet: A Complete Guide How I Almost Shipped My Credentials with Gemini 3 Flash in Google Antigravity The Agentic AI Security Universe: A Complete Guide to Securing Autonomous AI Systems How I Fixed My Neck Which Started Breaking Before My Career Did Using AI Mastering OpenClaw: How This Autonomous Agent Framework Actually Works The Model Too Dangerous to Release— And Why Anthropic Is Talking to the US Government About It Demystifying BM25: The Algorithm That Powers Search Step-by-Step Guide to Building AI Agents Using LLMs Gradient Descent — An Explanation Your AI Agent Isn’t Dumb. It Has ADHD 10 AI Startups Changing the World in 2026 (Nobody Is Talking About These Yet)_Part 5
Stop Writing Messy Validation Code: A Beginner-Friendly Guide to Pydantic in Python
Shubham Chou · 2026-04-27 · via Artificial Intelligence in Plain English - Medium
Pydantic Beginner Guide When you build Python applications, you often receive data from many places: APIs, forms, JSON files, databases, CSV files, user inputs, or environment variables. The problem is simple: You cannot always trust the data. Maybe the age comes as "25" instead of 25. Maybe an email field is missing. Maybe price is negative. Maybe an API sends extra fields you do not need. Without validation, your program may break later in confusing ways. That is where Pydantic helps. Pydantic is a Python library used for data validation, parsing, and serialization using normal Python type hints. The official documentation describes it as being powered by type hints, with validation and serialization controlled by annotations, and its core validation logic is written in Rust for speed. What Is Pydantic? pydantic Pydantic lets you define the structure of your data using Python classes. Instead of manually writing many if conditions, you describe what the data should look like, and Pydantic checks it for you. Example: from pydantic import BaseModel class User(BaseModel): name: str age: int email: str user = User(name="Shubham", age="25", email="test@example.com") print(user) print(type(user.age)) Output: name='Shubham' age=25 email='test@example.com' <class 'int'> Notice something important. We passed age as a string: age="25" But Pydantic converted it into an integer: 25 This is one of the biggest reasons Pydantic is useful. It validates and also parses data into the correct type. Why Should You Use Pydantic? You should use Pydantic when your code depends on data being correct. Without Pydantic, you may write code like this: def create_user(data): if "name" not in data: raise ValueError("name is required") if "age" not in data: raise ValueError("age is required") if not isinstance(data["age"], int): raise ValueError("age must be an integer") return data This becomes messy very quickly. With Pydantic: from pydantic import BaseModel class User(BaseModel): name: str age: int data = {"name": "Amit", "age": 30} user = User(**data) print(user) Cleaner. Safer. Easier to read. Pydantic is especially useful because it supports validation, serialization to dictionaries or JSON, and JSON schema generation for integration with tools and APIs. Where Is Pydantic Useful? Pydantic is useful in many real-world Python projects. Pydantic Usefulness 1. API Development If you are using FastAPI , Pydantic is commonly used to validate request and response data. Example: from pydantic import BaseModel class Product(BaseModel): name: str price: float in_stock: bool incoming_data = { "name": "Laptop", "price": "59999.99", "in_stock": "true" } product = Product(**incoming_data) print(product) print(type(product.price)) print(type(product.in_stock)) Output: name='Laptop' price=59999.99 in_stock=True <class 'float'> <class 'bool'> This is very useful when APIs send data in string format. 2. Validating JSON Data Suppose you receive JSON from an external API: api_response = { "id": 101, "username": "john_doe", "followers": "1200" } You can validate it like this: from pydantic import BaseModel class Profile(BaseModel): id: int username: str followers: int profile = Profile(**api_response) print(profile.followers) print(type(profile.followers)) Output: 1200 <class 'int'> Your code now works with clean data. 3. Data Pipelines and ETL In data engineering or analytics, bad data is common. Example: from pydantic import BaseModel, Field class SalesRecord(BaseModel): order_id: int customer_name: str amount: float = Field(gt=0) country: str record = SalesRecord( order_id="1001", customer_name="Rahul", amount=499.99, country="India" ) print(record) Here: amount: float = Field(gt=0) means amount must be greater than zero. If someone passes a negative amount: from pydantic import ValidationError try: bad_record = SalesRecord( order_id="1002", customer_name="Aman", amount=-50, country="India" ) except ValidationError as e: print(e) Pydantic will show a clear validation error. The Field() function lets you add constraints such as minimum value, maximum value, string length, default values, and descriptions. 4. Configuration and Settings Pydantic is also useful for managing application settings. For example, instead of hardcoding database settings everywhere, you can define a clean settings model. from pydantic import BaseModel class AppConfig(BaseModel): app_name: str debug: bool database_url: str max_connections: int config = AppConfig( app_name="My App", debug="true", database_url="postgresql://localhost:5432/mydb", max_connections="10" ) print(config) Output: app_name='My App' debug=True database_url='postgresql://localhost:5432/mydb' max_connections=10 This helps make your application more reliable. Understanding BaseModel Most beginner Pydantic code starts with BaseModel. from pydantic import BaseModel BaseModel is the base class that gives your class validation power. Example: class Student(BaseModel): name: str marks: int passed: bool This tells Pydantic: name should be a string marks should be an integer passed should be a boolean Now you can create a validated object: student = Student(name="Priya", marks="85", passed="true") print(student) Output: name='Priya' marks=85 passed=True Handling Validation Errors When invalid data is passed, Pydantic raises a ValidationError. from pydantic import BaseModel, ValidationError class Employee(BaseModel): name: str salary: float try: employee = Employee(name="Ravi", salary="not-a-number") except ValidationError as e: print(e) Output will explain what went wrong. This is better than your application failing later with confusing bugs. Using Field for Better Validation Field allows you to add rules. from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(min_length=3, max_length=20) age: int = Field(ge=18) Here: min_length=3 means username must have at least 3 characters. ge=18 means age must be greater than or equal to 18. Example: try: user = User(username="ab", age=16) except ValidationError as e: print(e) This will fail because: username is too short age is below 18 Nested Models: Validating Complex Data Pydantic is very useful when your data has nested structure. Example: from pydantic import BaseModel class Address(BaseModel): city: str country: str pincode: int class Customer(BaseModel): name: str address: Address data = { "name": "Sneha", "address": { "city": "Bangalore", "country": "India", "pincode": "560001" } } customer = Customer(**data) print(customer) print(type(customer.address.pincode)) Output: name='Sneha' address=Address(city='Bangalore', country='India', pincode=560001) <class 'int'> This is powerful for APIs, JSON files, and real-world applications. Converting Pydantic Models to Dictionary or JSON Pydantic models can be converted into dictionaries or JSON. In Pydantic v2, model_dump() is commonly used to convert a model to a dictionary, and Pydantic documentation explains serialization as converting models into Python or JSON-compatible outputs. from pydantic import BaseModel class Book(BaseModel): title: str author: str price: float book = Book(title="Python Basics", author="John Smith", price=499.99) book_dict = book.model_dump() book_json = book.model_dump_json() print(book_dict) print(book_json) Output: {'title': 'Python Basics', 'author': 'John Smith', 'price': 499.99} {"title":"Python Basics","author":"John Smith","price":499.99} This is useful when sending data back to APIs, storing data, or logging clean outputs. Custom Validation Example Sometimes basic type checking is not enough. For example, you may want to reject usernames containing spaces. from pydantic import BaseModel, field_validator, ValidationError class Account(BaseModel): username: str @field_validator("username") @classmethod def username_must_not_have_spaces(cls, value): if " " in value: raise ValueError("username must not contain spaces") return value try: account = Account(username="john doe") except ValidationError as e: print(e) This gives you full control over validation logic. Real-World Example: Validating an API Request Imagine you are building an e-commerce checkout system. from pydantic import BaseModel, Field from typing import List class Item(BaseModel): product_id: int name: str quantity: int = Field(gt=0) price: float = Field(gt=0) class Order(BaseModel): order_id: int customer_email: str items: List[Item] order_data = { "order_id": "5001", "customer_email": "customer@example.com", "items": [ { "product_id": "101", "name": "Keyboard", "quantity": 2, "price": "1499.99" }, { "product_id": 102, "name": "Mouse", "quantity": 1, "price": 799.50 } ] } order = Order(**order_data) print(order) print(order.model_dump()) Pydantic validates the full order, including the nested item list. This is exactly where Pydantic becomes valuable: APIs, checkout systems, dashboards, data pipelines, ML apps, and backend services. When Should You Not Use Pydantic? Pydantic is powerful, but you do not need it everywhere. You may not need Pydantic for: Very small scripts Simple variables inside one function Code where data is already fully controlled Performance-critical loops where millions of objects are created repeatedly But when your app receives external or unpredictable data, Pydantic is usually a smart choice. Pydantic vs Manual Validation Why Use Pydantic? Manual validation: if not isinstance(age, int): raise ValueError("Age must be integer") Pydantic validation: class User(BaseModel): age: int Manual validation becomes harder as your data grows. Pydantic keeps your code clean because the validation rules stay close to the data structure. Beginner Mental Model Think of Pydantic like a security guard for your data . Before data enters your application, Pydantic checks: Is the required field present? Is the type correct? Can it be converted safely? Does it follow rules like minimum length or positive number? Is the nested structure valid? Only clean data gets through. Final Takeaway Pydantic is one of the most useful libraries for writing reliable Python applications. It helps you: Validate incoming data Convert data into correct types Catch errors early Reduce manual if checks Work cleanly with APIs and JSON Serialize data into dictionaries or JSON Build safer backend, data, and ML applications If you are learning Python seriously, especially for APIs, data engineering, automation, or AI apps, Pydantic is worth learning early. Sources: Official Documentation Pydantic Docs — https://docs.pydantic.dev GitHub Repository (Code + Examples) Pydantic GitHub — https://github.com/pydantic/pydantic A quick note before you go 👋 I break down real AI shifts before they hit the mainstream 🚀 Click Follow now so you do not miss what matters next and drop a clap 👏 if this helped. Stop Writing Messy Validation Code: A Beginner-Friendly Guide to Pydantic in Python was originally published in Artificial Intelligence in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.