Python Cookbook
Recipes for Python. Hands-on code examples, snippets and guides for daily work.
Language Core (语言核心)
General
- Flatten a nested sequence
- Unpacking Elements from Iterables
- Finding the Largest or Smallest N Items
- Implementing a Priority Queue
- Calculating with Dictionarie
- Finding Commonalities in Two Dictionaries
- Sorting Objects Without Native Comparison Support
- Grouping Records Together Based on a Field
Text Processing (文本处理)
Extended Type (拓展类型)
- Tuples with Named Fields -
namedtuple(命名元组) - Ordered Dictionary -
OrderedDict - Data Classes -
dataclasses(数据类)
Date & Time (日期时间)
- Time: Timestamp (UNIX Time), UTC, Local Time
- Time Zone
- Representation
Decorator (装饰器)
- Function (Method) Decorator
- Function Decorator Without Argument
- Function Decorator With Required Arguments
- Function Decorator With Optional Arguments
- Class Decorator
Context Manager (上下文管理器)
withStatement- Context Manager
- Multiple Context Managers
- Context Manager Protocol
- Single Use Context Manager
- Reentrant Context Manager
- Reusable Context Manager
Exception Handling
Type Hint / Type Annotation (类型提示/类型注解)
- Type Hint
- Basic Types
- Union Types:
|,,typing.Uniontyping.Optional - Constants and Class Attributes:
typing.Final TypedDictnamedtuple:typing.NamedTupleitertools.chain- socket
- Regex
- Literal:
typing.Literal - Any:
typing.Anyandobject - Type objects
- Type Alias
- Callable objects
- Class Variables:
typing.ClassVar - Restricting Inheritance and Overriding:
@typing.final typing.NoReturn- Generic Function and Class
- Override
I/O, File-Like Object
- Inheritance of File Descriptor
- File Object (I/O)
- Text I/O
- Binary I/O
open()Reference Implementation
Logging (日志)
Networks and Communications (网络通信)
socketserverClass Diagram- TCP Server (IPv4)
- TCP Client (IPv4)
- I/O Multiplex (I/O多路复用) (Server)
- I/O Multiplex (I/O多路复用) (Client)
- Pack/Unpack Binary Data -
struct
Parallelism and Concurrent (并发)
- Processes-Based Concurrent (High-Level API)
- Multi-Processes Parallelism for CPU-bound tasks (Low-Level API:
multiprocessing)
Asynchronous I/O (异步 I/O)
- Coroutine (协程)
- Concurrent Coroutines (or Tasks) (并行协程)
- Timeout
- Waiting Primitives
- Queue (队列)
- Scheduled Tasks (调度任务)
- TCP Server (Low-Level APIs)
- TCP Client (Low-Level APIs)
System
Build (构建)
Command-Line Arguments Parser
argparse(deprecated since Python 3.2)optparse: C-Style Parsergetopt
Package Management
pip- Standard Package Manageruv- Fast Python package and project managerpipx- Install and Run Python Applications- Virtual Environment Managerpipenv
Project
- Project:
pyproject.toml Ruff- Linter and Code Formatterblack- Code Formatterisort- Sort Importsmypy- Type Checkerpylint- Linter
Test
Performance
Deploy
Web Development
- URL Parsing:
urllib.parse - HTTP Datetime Format
- HTTP Cookie (Server Side):
http.cookies - ASGI / WSGI /
CGI - IDNA (Internationalized Domain Names in Applications, 国际化域名应用)
HTTP Client/Request
urllib.request(builtin)aiohttp: asynciorequests: sync io, usingurllib3
Web Frameworks
FastAPI: ASGI + type annotations + data model + OpenAPI(Swagger UI)Django: full-featuredFlask: tiny
Web Server
http.server(builtin)aiohttp: asyncio, APIuvicorn: ASGI, WebSocketsHypercorn: HTTP/2, HTTP/3uWSGI: WSGI, HTTP/2
Task Queue
System Services Driver
MongoDB
- Official Driver
- ODM
Redis
redis-py: Sync + Asyncaioredis: Async (Obsoleted byredis-py)pyton-redis-orm: ORM
RabbitMQ
IoT
MQTT
TODO: Language Core (语言核心)
- Parallelism and Concurrent (并发)
- Multi-Threads Parallelism for I/O-bound tasks
- Multi-Processes - Queue (队列)
- High-Level Threads-Based Concurrent
- Synchronization Primitives -
Event(For Processes and Threads) - Synchronization Primitives - Mutex Lock (互斥锁):
Lock(For Processes and Threads) - Synchronization Primitives - Reentrant Lock (重入锁):
RLock - Synchronization Primitives - Condition Variable (条件变量):
Condition(For Processes and Threads) - Synchronization Primitives - Semaphore (信号量):
Semaphore/BoundedSemaphore(For Processes and Threads) - Synchronization Primitives - (栅栏):
Barrier
- Networks and Communications (网络通信)
- Asynchronous I/O (异步 I/O)
- Setup Python Project