python-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Development

Python开发

Core Python language concepts, idioms, and best practices.
Python 核心语言概念、惯用写法与最佳实践。

Core Expertise

核心专业技能

  • Python Language: Modern Python 3.10+ features and idioms
  • Best Practices: Pythonic code, design patterns, SOLID principles
  • Debugging: Interactive debugging and profiling techniques
  • Performance: Optimization strategies and profiling
  • Async Programming: async/await patterns and asyncio
  • Python语言: 现代Python 3.10+版本特性与惯用写法
  • 最佳实践: Pythonic代码、设计模式、SOLID原则
  • 调试: 交互式调试与性能分析技术
  • 性能: 优化策略与性能剖析
  • 异步编程: async/await模式与asyncio

Modern Python Features (3.10+)

现代Python特性(3.10+)

Type Hints

类型提示

python
undefined
python
undefined

Modern syntax (Python 3.10+)

Modern syntax (Python 3.10+)

def process_items( items: list[str], # Not List[str] mapping: dict[str, int], # Not Dict[str, int] optional: str | None = None, # Not Optional[str] ) -> tuple[bool, str]: # Not Tuple[bool, str] """Process items with modern type hints.""" return True, "success"
def process_items( items: list[str], # Not List[str] mapping: dict[str, int], # Not Dict[str, int] optional: str | None = None, # Not Optional[str] ) -> tuple[bool, str]: # Not Tuple[bool, str] """Process items with modern type hints.""" return True, "success"

Type aliases

Type aliases

type UserId = int type UserDict = dict[str, str | int]
def get_user(user_id: UserId) -> UserDict: return {"id": user_id, "name": "Alice"}
undefined
type UserId = int type UserDict = dict[str, str | int]
def get_user(user_id: UserId) -> UserDict: return {"id": user_id, "name": "Alice"}
undefined

Pattern Matching (3.10+)

模式匹配(3.10+)

python
def handle_command(command: dict) -> str:
    match command:
        case {"action": "create", "item": item}:
            return f"Creating {item}"
        case {"action": "delete", "item": item}:
            return f"Deleting {item}"
        case {"action": "list"}:
            return "Listing items"
        case _:
            return "Unknown command"
python
def handle_command(command: dict) -> str:
    match command:
        case {"action": "create", "item": item}:
            return f"Creating {item}"
        case {"action": "delete", "item": item}:
            return f"Deleting {item}"
        case {"action": "list"}:
            return "Listing items"
        case _:
            return "Unknown command"

Structural Pattern Matching

结构化模式匹配

python
def process_response(response):
    match response:
        case {"status": 200, "data": data}:
            return process_success(data)
        case {"status": 404}:
            raise NotFoundError()
        case {"status": code} if code >= 500:
            raise ServerError(code)
python
def process_response(response):
    match response:
        case {"status": 200, "data": data}:
            return process_success(data)
        case {"status": 404}:
            raise NotFoundError()
        case {"status": code} if code >= 500:
            raise ServerError(code)

Python Idioms

Python惯用写法

Context Managers

上下文管理器

python
undefined
python
undefined

File handling

File handling

with open("file.txt") as f: content = f.read()
with open("file.txt") as f: content = f.read()

Custom context manager

Custom context manager

from contextlib import contextmanager
@contextmanager def database_connection(): conn = create_connection() try: yield conn finally: conn.close()
with database_connection() as conn: conn.execute("SELECT * FROM users")
undefined
from contextlib import contextmanager
@contextmanager def database_connection(): conn = create_connection() try: yield conn finally: conn.close()
with database_connection() as conn: conn.execute("SELECT * FROM users")
undefined

List Comprehensions

列表推导式

python
undefined
python
undefined

List comprehension

List comprehension

squares = [x**2 for x in range(10)]
squares = [x**2 for x in range(10)]

Dict comprehension

Dict comprehension

word_lengths = {word: len(word) for word in ["hello", "world"]}
word_lengths = {word: len(word) for word in ["hello", "world"]}

Set comprehension

Set comprehension

unique_lengths = {len(word) for word in ["hello", "world", "hi"]}
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}

Generator expression

Generator expression

sum_of_squares = sum(x**2 for x in range(1000000)) # Memory efficient
undefined
sum_of_squares = sum(x**2 for x in range(1000000)) # Memory efficient
undefined

Iterators and Generators

迭代器与生成器

python
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
python
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

Use generator

Use generator

fib = fibonacci() first_ten = [next(fib) for _ in range(10)]
fib = fibonacci() first_ten = [next(fib) for _ in range(10)]

Generator expression

Generator expression

even_squares = (x**2 for x in range(10) if x % 2 == 0)
undefined
even_squares = (x**2 for x in range(10) if x % 2 == 0)
undefined

Debugging

调试

Interactive Debugging

交互式调试

python
import pdb

def problematic_function():
    value = calculate()
    pdb.set_trace()  # Debugger breakpoint
    return process(value)
bash
undefined
python
import pdb

def problematic_function():
    value = calculate()
    pdb.set_trace()  # Debugger breakpoint
    return process(value)
bash
undefined

Debug on error

Debug on error

python -m pdb script.py
python -m pdb script.py

pytest with debugger

pytest with debugger

uv run pytest --pdb # Drop into pdb on failure uv run pytest --pdb --pdbcls=IPython.terminal.debugger:TerminalPdb
undefined
uv run pytest --pdb # Drop into pdb on failure uv run pytest --pdb --pdbcls=IPython.terminal.debugger:TerminalPdb
undefined

Performance Profiling

性能分析

bash
undefined
bash
undefined

CPU profiling

CPU profiling

uv run python -m cProfile -s cumtime script.py | head -20
uv run python -m cProfile -s cumtime script.py | head -20

Line-by-line profiling (temporary dependency)

Line-by-line profiling (temporary dependency)

uv run --with line-profiler kernprof -l -v script.py
uv run --with line-profiler kernprof -l -v script.py

Memory profiling (temporary dependency)

Memory profiling (temporary dependency)

uv run --with memory-profiler python -m memory_profiler script.py
uv run --with memory-profiler python -m memory_profiler script.py

Real-time profiling (ephemeral tool)

Real-time profiling (ephemeral tool)

uvx py-spy top -- python script.py
uvx py-spy top -- python script.py

Quick profiling with scalene

Quick profiling with scalene

uv run --with scalene python -m scalene script.py
undefined
uv run --with scalene python -m scalene script.py
undefined

Built-in Debugging Tools

内置调试工具

python
undefined
python
undefined

Trace execution

Trace execution

import sys
def trace_calls(frame, event, arg): if event == 'call': print(f"Calling {frame.f_code.co_name}") return trace_calls
sys.settrace(trace_calls)
import sys
def trace_calls(frame, event, arg): if event == 'call': print(f"Calling {frame.f_code.co_name}") return trace_calls
sys.settrace(trace_calls)

Memory tracking

Memory tracking

import tracemalloc
tracemalloc.start()
import tracemalloc
tracemalloc.start()

... code to profile

... code to profile

snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') for stat in top_stats[:10]: print(stat)
undefined
snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') for stat in top_stats[:10]: print(stat)
undefined

Async Programming

异步编程

Basic async/await

基础async/await

python
import asyncio

async def fetch_data(url: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.json()

async def main():
    result = await fetch_data("https://api.example.com")
    print(result)

asyncio.run(main())
python
import asyncio

async def fetch_data(url: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.json()

async def main():
    result = await fetch_data("https://api.example.com")
    print(result)

asyncio.run(main())

Concurrent Tasks

并发任务

python
async def process_multiple():
    # Run concurrently
    results = await asyncio.gather(
        fetch_data("url1"),
        fetch_data("url2"),
        fetch_data("url3"),
    )
    return results
python
async def process_multiple():
    # Run concurrently
    results = await asyncio.gather(
        fetch_data("url1"),
        fetch_data("url2"),
        fetch_data("url3"),
    )
    return results

With timeout

With timeout

async def with_timeout(): try: result = await asyncio.wait_for(fetch_data("url"), timeout=5.0) except asyncio.TimeoutError: print("Request timed out")
undefined
async def with_timeout(): try: result = await asyncio.wait_for(fetch_data("url"), timeout=5.0) except asyncio.TimeoutError: print("Request timed out")
undefined

Design Patterns

设计模式

Dependency Injection

依赖注入

python
from typing import Protocol

class Database(Protocol):
    def query(self, sql: str) -> list: ...

def get_users(db: Database) -> list:
    return db.query("SELECT * FROM users")
python
from typing import Protocol

class Database(Protocol):
    def query(self, sql: str) -> list: ...

def get_users(db: Database) -> list:
    return db.query("SELECT * FROM users")

Factory Pattern

工厂模式

python
def create_handler(handler_type: str):
    match handler_type:
        case "json":
            return JSONHandler()
        case "xml":
            return XMLHandler()
        case _:
            raise ValueError(f"Unknown handler: {handler_type}")
python
def create_handler(handler_type: str):
    match handler_type:
        case "json":
            return JSONHandler()
        case "xml":
            return XMLHandler()
        case _:
            raise ValueError(f"Unknown handler: {handler_type}")

Decorator Pattern

装饰器模式

python
from functools import wraps
import time

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
python
from functools import wraps
import time

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

Best Practices

最佳实践

SOLID Principles

SOLID原则

Single Responsibility:
python
undefined
单一职责原则:
python
undefined

Bad: Class does too much

Bad: Class does too much

class User: def save(self): pass def send_email(self): pass def generate_report(self): pass
class User: def save(self): pass def send_email(self): pass def generate_report(self): pass

Good: Separate concerns

Good: Separate concerns

class User: def save(self): pass
class EmailService: def send_email(self, user): pass
class ReportGenerator: def generate(self, user): pass
undefined
class User: def save(self): pass
class EmailService: def send_email(self, user): pass
class ReportGenerator: def generate(self, user): pass
undefined

Fail Fast

快速失败

python
def process_data(data: dict) -> str:
    # Validate early
    if not data:
        raise ValueError("Data cannot be empty")
    if "required_field" not in data:
        raise KeyError("Missing required field")

    # Process with confidence
    return data["required_field"].upper()
python
def process_data(data: dict) -> str:
    # Validate early
    if not data:
        raise ValueError("Data cannot be empty")
    if "required_field" not in data:
        raise KeyError("Missing required field")

    # Process with confidence
    return data["required_field"].upper()

Functional Approach

函数式编程方法

python
undefined
python
undefined

Prefer immutable transformations

Prefer immutable transformations

def process_items(items: list[int]) -> list[int]: return [item * 2 for item in items] # New list
def process_items(items: list[int]) -> list[int]: return [item * 2 for item in items] # New list

Over mutations

Over mutations

def process_items_bad(items: list[int]) -> None: for i in range(len(items)): items[i] *= 2 # Mutates input
undefined
def process_items_bad(items: list[int]) -> None: for i in range(len(items)): items[i] *= 2 # Mutates input
undefined

Project Structure (src layout)

项目结构(src布局)

my-project/
├── pyproject.toml
├── README.md
├── src/
│   └── my_project/
│       ├── __init__.py
│       ├── core.py
│       ├── utils.py
│       └── models.py
└── tests/
    ├── conftest.py
    ├── test_core.py
    └── test_utils.py
my-project/
├── pyproject.toml
├── README.md
├── src/
│   └── my_project/
│       ├── __init__.py
│       ├── core.py
│       ├── utils.py
│       └── models.py
└── tests/
    ├── conftest.py
    ├── test_core.py
    └── test_utils.py

See Also

另请参阅

  • uv-run - Running scripts, temporary dependencies, PEP 723
  • uv-project-management - Project setup and dependency management
  • uv-tool-management - Installing CLI tools globally
  • python-testing - Testing with pytest
  • python-code-quality - Linting and type checking with ruff/ty
  • python-packaging - Building and publishing packages
  • uv-python-versions - Managing Python interpreters
  • uv-run - 运行脚本、临时依赖管理、PEP 723
  • uv-project-management - 项目配置与依赖管理
  • uv-tool-management - 全局安装CLI工具
  • python-testing - 使用pytest进行测试
  • python-code-quality - 使用ruff/ty进行代码检查与类型校验
  • python-packaging - 构建与发布包
  • uv-python-versions - 管理Python解释器

References

参考资料