Chuyển đến nội dung
Skillpedia
Lập trình chung280k · #228

python-patterns

Skill này làm gì

Hướng dẫn này dạy cách viết code Python rõ ràng, hiệu quả và dễ hiểu bằng cách tuân theo thực hành tốt nhất. Nó bao gồm cách tổ chức code, dùng type hint để rõ ràng hơn và xử lý lỗi một cách thông minh.

Khi nào nên dùng

  • ✓Khi viết code Python mới.
  • ✓Khi xem lại code của người khác.
  • ✓Khi muốn cải thiện code hiện có.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/python-patterns/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/python-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để viết một hàm Python dễ đọc, trả về chỉ những người dùng đang hoạt động từ một danh sách?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó đưa ra ví dụ về code tốt và chưa tốt để minh họa các nguyên tắc. Nó giải thích cách dùng 'type hint' để chỉ rõ kiểu dữ liệu mong đợi và cách dùng 'context manager' để quản lý tài nguyên như tệp.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Python Development Patterns

Idiomatic Python patterns and best practices for building robust, efficient, and maintainable applications.

When to Activate

  • Writing new Python code
  • Reviewing Python code
  • Refactoring existing Python code
  • Designing Python packages/modules

Core Principles

1. Readability Counts

Python prioritizes readability. Code should be obvious and easy to understand.

# Good: Clear and readable
def get_active_users(users: list[User]) -> list[User]:
    """Return only active users from the provided list."""
    return [user for user in users if user.is_active]


# Bad: Clever but confusing
def get_active_users(u):
    return [x for x in u if x.a]

2. Explicit is Better Than Implicit

Avoid magic; be clear about what your code does.

# Good: Explicit configuration
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Bad: Hidden side effects
import some_module
some_module.setup()  # What does this do?

3. EAFP - Easier to Ask Forgiveness Than Permission

Python prefers exception handling over checking conditions.

# Good: EAFP style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
    try:
        return dictionary[key]
    except KeyError:
        return default_value

# Bad: LBYL (Look Before You Leap) style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
    if key in dictionary:
        return dictionary[key]
    else:
        return default_value

Type Hints

Basic Type Annotations

from typing import Optional, List, Dict, Any

def process_user(
    user_id: str,
    data: Dict[str, Any],
    active: bool = True
) -> Optional[User]:
    """Process a user and return the updated User or None."""
    if not active:
        return None
    return User(user_id, data)

Modern Type Hints (Python 3.9+)

# Python 3.9+ - Use built-in types
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Python 3.8 and earlier - Use typing module
from typing import List, Dict

def process_items(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

Type Aliases and TypeVar

from typing import TypeVar, Union

# Type alias for complex types
JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]

def parse_json(data: str) -> JSON:
    return json.loads(data)

# Generic types
T = TypeVar('T')

def first(items: list[T]) -> T | None:
    """Return the first item or None if list is empty."""
    return items[0] if items else None

Protocol-Based Duck Typing

from typing import Protocol

class Renderable(Protocol):
    def render(self) -> str:
        """Render the object to a string."""

def render_all(items: list[Renderable]) -> str:
    """Render all items that implement the Renderable protocol."""
    return "\n".join(item.render() for item in items)

Error Handling Patterns

Specific Exception Handling

# Good: Catch specific exceptions
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except FileNotFoundError as e:
        raise ConfigError(f"Config file not found: {path}") from e
    except json.JSONDecodeError as e:
        raise ConfigError(f"Invalid JSON in config: {path}") from e

# Bad: Bare except
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except:
        return None  # Silent failure!

Exception Chaining

def process_data(data: str) -> Result:
    try:
        parsed = json.loads(data)
    except json.JSONDecodeError as e:
        # Chain exceptions to preserve the traceback
        raise ValueError(f"Failed to parse data: {data}") from e

Custom Exception Hierarchy

class AppError(Exception):
    """Base exception for all application errors."""
    pass

class ValidationError(AppError):
    """Raised when input validation fails."""
    pass

class NotFoundError(AppError):
    """Raised when a requested resource is not found."""
    pass

# Usage
def get_user(user_id: str) -> User:
    user = db.find_user(user_id)
    if not user:
        raise NotFoundError(f"User not found: {user_id}")
    return user

Context Managers

…

Câu hỏi thường gặp

'Type hint' là gì?

'Type hint' là các chú thích trong code cho biết một biến hoặc hàm mong đợi loại thông tin nào (ví dụ văn bản, số) và trả về loại nào. Điều này giúp ngăn lỗi và làm code dễ hiểu hơn.

'EAFP' nghĩa là gì?

'EAFP' là viết tắt của 'Easier to Ask Forgiveness Than Permission' (dễ xin lỗi hơn là xin phép). Trong lập trình, nghĩa là thử làm việc gì đó và xử lý lỗi nếu có, thay vì kiểm tra mọi điều kiện trước khi thử.

'Context manager' là gì?

'Context manager' là công cụ giúp quản lý tài nguyên, như tự động mở và đóng tệp. Chúng đảm bảo tài nguyên được giải phóng đúng cách, ngay cả khi có lỗi xảy ra.

Chi tiết

Mô tả gốc của tác giả

Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications. Use when writing or reviewing Python code and idiomatic structure, typing, or PEP 8 is in question.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#228
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự