Langsung ke konten
Skillpedia
Pemrograman umum280k · #228

python-patterns

Fungsinya

Panduan ini mengajarkan cara menulis kode Python yang jelas, efisien, dan mudah dipahami dengan mengikuti praktik terbaik. Panduan ini membahas cara mengatur kode, menggunakan type hints agar lebih jelas, dan menangani error dengan cerdas.

Kapan dipakai

  • ✓Saat menulis kode Python baru.
  • ✓Saat meninjau kode milik orang lain.
  • ✓Saat ingin memperbaiki kode yang sudah ada.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/python-patterns/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit →

Contoh permintaan ke AI

“Bagaimana cara menulis fungsi Python yang mudah dibaca dan hanya mengembalikan user yang aktif dari sebuah daftar?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Panduan ini menampilkan contoh kode yang baik dan yang buruk untuk menjelaskan prinsip-prinsipnya. Panduan ini juga menjelaskan penggunaan 'type hints' untuk menunjukkan tipe data yang diharapkan, serta cara menggunakan 'context managers' untuk mengelola resource seperti file.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari GitHub.

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

…

Pertanyaan umum

Apa itu 'type hints'?

'Type hints' adalah anotasi dalam kode yang menjelaskan jenis informasi yang diharapkan oleh sebuah variabel atau fungsi (misalnya teks atau angka) serta jenis data yang dikembalikannya. Hal ini membantu mencegah error dan membuat kode lebih mudah dipahami.

Apa arti 'EAFP'?

'EAFP' adalah singkatan dari 'Easier to Ask Forgiveness Than Permission', yang artinya lebih mudah meminta maaf daripada meminta izin. Dalam pemrograman, ini berarti lebih baik langsung mencoba melakukan sesuatu dan menangani error jika terjadi, daripada memeriksa semua kemungkinan kondisi terlebih dahulu.

Apa itu 'context managers'?

'Context managers' adalah alat yang membantu mengelola resource, misalnya membuka dan menutup file secara otomatis. Alat ini memastikan resource dilepaskan dengan benar, bahkan ketika terjadi error.

Detail

Deskripsi asli dari pembuat

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

Popularitas

Bintang GitHub
280k
Peringkat
#228
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa