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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
V
V2EX
博客园 - 【当耐特】
WordPress大学
WordPress大学
爱范儿
爱范儿
美团技术团队
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
量子位
Hugging Face - Blog
Hugging Face - Blog
B
Blog RSS Feed
Recorded Future
Recorded Future
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
H
Hackread – Cybersecurity News, Data Breaches, AI and More
腾讯CDC
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
博客园 - 叶小钗
GbyAI
GbyAI
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Full Disclosure
G
Google Developers Blog
D
Docker
T
Tailwind CSS Blog
C
Check Point Blog
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
T
The Blog of Author Tim Ferriss
B
Blog
博客园 - 三生石上(FineUI控件)
博客园 - Franky
H
Help Net Security
MyScale Blog
MyScale Blog
U
Unit 42
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
L
LangChain Blog
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation A Coding Guide on LLM Post Training with TRL from Supervised Fine Tuning to DPO and GRPO Reasoning Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing
Sana Hassan · 2026-04-30 · via MarkTechPost

In this tutorial, we explore Pyright, Microsoft’s high-performance static type checker for Python, and walk through its most powerful features in a hands-on, Colab-friendly format. We start from the ground up with basic annotations and type inference, then progressively advance through Union types, type narrowing, generics, Protocols, TypedDict, dataclasses, and modern typing constructs like Self, TypeAlias, and NewType. We also examine how strict mode raises the bar for type safety across an entire codebase and how pyrightconfig.json provides fine-grained control over diagnostic rules at the project level. Also, we deliberately introduce both correct and intentionally broken code to see exactly how Pyright catches real-world mistakes before they ever reach runtime.

import subprocess, sys, json, textwrap, os


subprocess.check_call([sys.executable, "-m", "pip", "install", "pyright", "-q"])
print("✅  pyright installed\n")


WORK = "/tmp/pyright_tutorial"
os.makedirs(WORK, exist_ok=True)


def write(filename: str, code: str) -> str:
   path = os.path.join(WORK, filename)
   os.makedirs(os.path.dirname(path), exist_ok=True)
   with open(path, "w") as f:
       f.write(textwrap.dedent(code))
   return path


def run_pyright(*files, mode="basic", extra_flags=None):
   args = [sys.executable, "-m", "pyright",
           "--outputjson",
           f"--pythonversion=3.11",
           f"--typeCheckingMode={mode}",
           *(extra_flags or []),
           *[os.path.join(WORK, f) for f in files]]
   result = subprocess.run(args, capture_output=True, text=True)
   try:
       data = json.loads(result.stdout)
   except json.JSONDecodeError:
       print(result.stdout or result.stderr)
       return
   diags = data.get("generalDiagnostics", [])
   summary = data.get("summary", {})
   print(f"  errors={summary.get('errorCount',0)}  "
         f"warnings={summary.get('warningCount',0)}  "
         f"infos={summary.get('informationCount',0)}")
   for d in diags:
       sev = d["severity"].upper()
       msg = d["message"]
       rule = d.get("rule", "")
       line = d["range"]["start"]["line"] + 1
       fname = os.path.basename(d["file"])
       tag = f"[{rule}]" if rule else ""
       print(f"    {sev} {fname}:{line} — {msg} {tag}")
   if not diags:
       print("    (no diagnostics — all clean ✅)")
   print()


print("=" * 62)
print("SECTION 1 · Basic annotations & inference")
print("=" * 62)


write("s1_basics.py", """
   def add(x: int, y: int) -> int:
       return x + y


   result: int = add(1, 2)


   bad: int = "hello"
   add(1, "two")
   add(1, 2, 3)


   def multiply(a: float, b: float):
       return a * b


   x: str = multiply(2.0, 3.0)
""")


print("→ s1_basics.py (basic mode):")
run_pyright("s1_basics.py")


print("=" * 62)
print("SECTION 2 · Optional / Union / PEP 604 syntax")
print("=" * 62)


write("s2_optional_union.py", """
   from typing import Optional, Union


   def greet(name: Optional[str] = None) -> str:
       if name is None:
           return "Hello, Guest"
       return f"Hello, {name}"


   greet("Alice")
   greet(None)
   greet(42)


   def stringify(val: Union[int, float, bool]) -> str:
       return str(val)


   stringify(3.14)
   stringify("x")


   def modern(val: int | str | None) -> str:
       return "" if val is None else str(val)


   modern(10)
   modern([])
""")


print("→ s2_optional_union.py:")
run_pyright("s2_optional_union.py")

We begin by installing Pyright and setting up two helper functions, write and run_pyright, which we reuse throughout subsequent sections to create typed Python files and parse Pyright’s JSON diagnostic output cleanly. We then move on to the basics of type annotations, deliberately passing incorrect argument types and mismatched assignments to observe exactly how Pyright flags each violation. We close this snippet by exploring Optional, Union, and the modern PEP 604 pipe syntax, confirming that Pyright correctly rejects values that fall outside the declared union of accepted types.

print("SECTION 3 · Type Narrowing")
print("=" * 62)


write("s3_narrowing.py", """
   from typing import Union
   import re


   def process(val: Union[int, str]) -> str:
       if isinstance(val, int):
           return str(val * 2)
       return val.upper()


   def safe_len(s: str | None) -> int:
       if s is None:
           return 0
       return len(s)


   def must_be_str(val: str | int) -> str:
       assert isinstance(val, str), "need string"
       return val.lower()


   from typing import TypeGuard


   def is_list_of_str(val: list[object]) -> TypeGuard[list[str]]:
       return all(isinstance(x, str) for x in val)


   def join_if_strings(lst: list[object]) -> str:
       if is_list_of_str(lst):
           return ", ".join(lst)
       return ""


   from typing import Literal, Never


   def assert_never(x: Never) -> Never:
       raise AssertionError(f"Unhandled: {x!r}")


   Status = Literal["ok", "error", "pending"]


   def handle(s: Status) -> str:
       match s:
           case "ok":      return "all good"
           case "error":   return "something failed"
           case "pending": return "waiting..."
""")


print("→ s3_narrowing.py:")
run_pyright("s3_narrowing.py")


print("=" * 62)
print("SECTION 4 · Generics, TypeVar, ParamSpec")
print("=" * 62)


write("s4_generics.py", """
   from typing import TypeVar, Generic, Callable, ParamSpec, Concatenate
   from collections.abc import Iterator


   T = TypeVar("T")
   S = TypeVar("S")
   P = ParamSpec("P")


   def first(lst: list[T]) -> T:
       return lst[0]


   x: int = first([1, 2, 3])
   y: str = first(["a", "b"])
   z: int = first(["a", "b"])


   class Stack(Generic[T]):
       def __init__(self) -> None:
           self._items: list[T] = []


       def push(self, item: T) -> None:
           self._items.append(item)


       def pop(self) -> T:
           return self._items.pop()


       def peek(self) -> T | None:
           return self._items[-1] if self._items else None


   int_stack: Stack[int] = Stack()
   int_stack.push(42)
   int_stack.push("oops")


   def logged(fn: Callable[P, T]) -> Callable[P, T]:
       def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
           print(f"calling {fn.__name__}")
           result = fn(*args, **kwargs)
           print(f"returned {result!r}")
           return result
       return wrapper


   @logged
   def add(a: int, b: int) -> int:
       return a + b


   add(1, 2)
   add("a", "b")


   Num = TypeVar("Num", int, float)


   def double(x: Num) -> Num:
       return x * 2  # type: ignore[operator]


   double(3)
   double(3.14)
   double("hi")
""")


print("→ s4_generics.py:")
run_pyright("s4_generics.py")

We dedicate this snippet first to type narrowing, one of Pyright’s most impressive capabilities, where we demonstrate how control-flow constructs such as isinstance, assert, TypeGuard, and structural match progressively refine a variable’s type within each branch. We then shift to generics, where we build a reusable Stack[T] class and a first() function to demonstrate how TypeVar enables type-safe code that works across multiple concrete types without sacrificing inference. We also introduce ParamSpec, which allows us to wrap functions with decorators while fully preserving the original callable’s argument and return type signatures.

print("=" * 62)
print("SECTION 5 · Protocols & Structural Subtyping")
print("=" * 62)


write("s5_protocols.py", """
   from typing import Protocol, runtime_checkable


   @runtime_checkable
   class Drawable(Protocol):
       def draw(self) -> str: ...
       def area(self) -> float: ...


   class Circle:
       def __init__(self, r: float) -> None:
           self.r = r
       def draw(self) -> str:
           return f"○  r={self.r}"
       def area(self) -> float:
           return 3.14159 * self.r ** 2


   class Rectangle:
       def __init__(self, w: float, h: float) -> None:
           self.w, self.h = w, h
       def draw(self) -> str:
           return f"▭  {self.w}×{self.h}"
       def area(self) -> float:
           return self.w * self.h


   def render(shape: Drawable) -> None:
       print(shape.draw(), f"area={shape.area():.2f}")


   render(Circle(5.0))
   render(Rectangle(3.0, 4.0))
   render("not a shape")


   from typing import TypeVar, Generic


   T_co = TypeVar("T_co", covariant=True)


   class Readable(Protocol[T_co]):
       def read(self) -> T_co: ...


   class FileStream:
       def read(self) -> bytes:
           return b"data"


   def consume(source: Readable[bytes]) -> bytes:
       return source.read()


   consume(FileStream())
""")


print("→ s5_protocols.py:")
run_pyright("s5_protocols.py")


print("=" * 62)
print("SECTION 6 · TypedDict, dataclasses, NamedTuple")
print("=" * 62)


write("s6_datastructures.py", """
   from typing import TypedDict, NotRequired, Required
   from dataclasses import dataclass, field
   from typing import NamedTuple


   class User(TypedDict):
       id: int
       name: str
       email: NotRequired[str]


   u1: User = {"id": 1, "name": "Alice"}
   u2: User = {"id": 2, "name": "Bob", "email": "b@x"}
   u3: User = {"id": "bad", "name": "Eve"}


   def print_user(u: User) -> None:
       print(u["name"], u.get("email", "—"))


   @dataclass
   class Product:
       sku: str
       price: float
       tags: list[str] = field(default_factory=list)
       discount: float = 0.0


       def final_price(self) -> float:
           return self.price * (1 - self.discount)


   p = Product(sku="ABC", price=9.99)
   p.price = 12.50
   p.price = "free"


   class Point(NamedTuple):
       x: float
       y: float
       label: str = ""


   pt = Point(1.0, 2.0)
   dist: float = (pt.x ** 2 + pt.y ** 2) ** 0.5
   pt.x = 5.0
""")


print("→ s6_datastructures.py:")
run_pyright("s6_datastructures.py")

We explore Protocols in this snippet, which provide us with structural subtyping: we can define an interface like Drawable and have Pyright accept any class that implements the required methods, without that class ever explicitly inheriting from the Protocol. We extend this further with a generic Readable[T] Protocol that combines structural checking with type parameters, showing how the two features compose naturally. We then turn to data structures, using TypedDict with NotRequired keys, @dataclass with typed fields, and NamedTuple to demonstrate how Pyright enforces type correctness across Python’s three most common structured-data patterns.

print("=" * 62)
print("SECTION 7 · Literal, Final, @overload")
print("=" * 62)


write("s7_literal_final_overload.py", """
   from typing import Literal, Final, overload


   Direction = Literal["north", "south", "east", "west"]


   def move(d: Direction, steps: int = 1) -> str:
       return f"Move {d} by {steps}"


   move("north")
   move("up")


   MAX_RETRIES: Final = 3
   MAX_RETRIES = 5


   class Config:
       DEBUG: Final[bool] = False
       VERSION: Final = "1.0.0"


   Config.DEBUG = True


   @overload
   def parse(value: str) -> int: ...
   @overload
   def parse(value: bytes) -> str: ...
   @overload
   def parse(value: int) -> float: ...


   def parse(value: str | bytes | int) -> int | str | float:
       if isinstance(value, str):
           return int(value)
       if isinstance(value, bytes):
           return value.decode()
       return float(value)


   a: int   = parse("42")
   b: str   = parse(b"hi")
   c: float = parse(99)
   d: int   = parse(99)
""")


print("→ s7_literal_final_overload.py:")
run_pyright("s7_literal_final_overload.py")


print("=" * 62)
print("SECTION 8 · Strict mode")
print("=" * 62)


write("s8_strict.py", """
   def no_annotation(x, y):
       return x + y


   class Bare:
       value = None


   def partial(x: int, y):
       return x
""")


print("→ s8_strict.py (strict mode):")
run_pyright("s8_strict.py", mode="strict")

We use Literal types here to restrict a function’s argument to a fixed set of string values, and we pair that with Final to show how Pyright prevents reassignment of constants at both the module and class level. We introduce @overload to define multiple distinct call signatures for a single function, allowing Pyright to resolve the correct return type based on the exact argument type the caller provides. We then switch to strict mode and run a deliberately under-annotated file through Pyright, which reveals just how many additional rules, missing return types, untyped parameters, and implicit Any strict mode activates compared to the default.

print("=" * 62)
print("SECTION 9 · pyrightconfig.json")
print("=" * 62)


config = {
   "include": ["src"],
   "exclude": ["**/__pycache__"],
   "pythonVersion": "3.11",
   "typeCheckingMode": "strict",
   "reportMissingImports": "error",
   "reportMissingTypeStubs": "warning",
   "reportUnknownVariableType": "warning",
   "reportUnknownMemberType": "warning",
   "reportUnnecessaryTypeIgnoreComment": "warning",
}
cfg_path = os.path.join(WORK, "pyrightconfig.json")
with open(cfg_path, "w") as f:
   json.dump(config, f, indent=2)
print(f"Written: {cfg_path}")
print(json.dumps(config, indent=2))
print()


print("=" * 62)
print("SECTION 10 · Self, TypeAlias, NewType")
print("=" * 62)


write("s10_modern_types.py", """
   from typing import Self, TypeAlias, NewType


   class Query:
       def __init__(self) -> None:
           self._filters: list[str] = []


       def where(self, cond: str) -> Self:
           self._filters.append(cond)
           return self


       def build(self) -> str:
           return " AND ".join(self._filters)


   class AdvancedQuery(Query):
       def order_by(self, col: str) -> Self:
           return self


   q = AdvancedQuery().where("age > 18").order_by("name")
   reveal_type(q)


   Vector: TypeAlias = list[float]
   Matrix: TypeAlias = list[Vector]


   def dot(a: Vector, b: Vector) -> float:
       return sum(x * y for x, y in zip(a, b))


   v1: Vector = [1.0, 2.0, 3.0]
   v2: Vector = [4.0, 5.0, 6.0]
   dot(v1, v2)
   dot(v1, [1, 2, 3])


   UserId   = NewType("UserId", int)
   OrderId  = NewType("OrderId", int)


   def get_user(uid: UserId) -> str:
       return f"user_{uid}"


   uid = UserId(42)
   oid = OrderId(99)


   get_user(uid)
   get_user(oid)
   get_user(42)
""")


print("→ s10_modern_types.py:")
run_pyright("s10_modern_types.py")


print("=" * 62)
print("SECTION 11 · reveal_type() & type: ignore")
print("=" * 62)


write("s11_reveal_ignore.py", """
   from typing import Any


   values = [1, "two", 3.0]
   reveal_type(values)


   def mystery(x: Any) -> Any:
       return x


   r = mystery(42)
   reveal_type(r)


   bad: int = "oops"
   bad2: int = "also bad"  # type: ignore[assignment]
""")


print("→ s11_reveal_ignore.py:")
run_pyright("s11_reveal_ignore.py")


print("=" * 62)
print("TUTORIAL COMPLETE")
print("=" * 62)
print("""
Topics covered
──────────────
1  Basic annotations & inference
2  Optional / Union / PEP 604 syntax
3  Type narrowing (isinstance, guards, TypeGuard, match)
4  Generics — TypeVar, Generic, ParamSpec
5  Protocols & structural subtyping
6  TypedDict, dataclasses, NamedTuple
7  Literal, Final, @overload
8  Strict mode
9  pyrightconfig.json
10  Self, TypeAlias, NewType
11  reveal_type() & type: ignore


All source files written to: /tmp/pyright_tutorial/
""")

We write a pyrightconfig.json file in this snippet to show how we configure Pyright at the project level, enabling strict mode globally and tuning individual diagnostic rules, such as reportMissingImports and reportUnknownMemberType, to either error or warning severity. We then work through three modern typing constructs: Self for fluent builder APIs that return the correct subclass type, TypeAlias for readable type-level naming, and NewType for creating nominally distinct types that Pyright refuses to mix even when their underlying representation is identical. 

In conclusion, we have covered eleven distinct areas of Pyright’s type system and come away with a clear picture of just how much safety and clarity static typing brings to Python codebases of any size. We have seen that Pyright goes well beyond simple annotation checking, it narrows types through control flow, enforces structural contracts through Protocols, preserves callable signatures through ParamSpec, and locks down constants through Final. We also maintained a practical workflow: we write typed code, run Pyright in basic or strict mode, interpret its JSON diagnostic output, and tune behavior via pyrightconfig.json.


Check out the Full Codes with Notebook here. Also, feel free to follow us on Twitter and don’t forget to join our 130k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us

Sana Hassan, a consulting intern at Marktechpost and dual-degree student at IIT Madras, is passionate about applying technology and AI to address real-world challenges. With a keen interest in solving practical problems, he brings a fresh perspective to the intersection of AI and real-life solutions.