jpskill.com
🛠️ 開発・MCP コミュニティ

python-style-guide

Comprehensive Python programming guidelines based on Google's Python Style Guide. Use when Claude needs to write Python code, review Python code for style issues, refactor Python code, or provide Python programming guidance. Covers language rules (imports, exceptions, type annotations), style rules (naming conventions, formatting, docstrings), and best practices for clean, maintainable Python code.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o python-style-guide.zip https://jpskill.com/download/17992.zip && unzip -o python-style-guide.zip && rm python-style-guide.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17992.zip -OutFile "$d\python-style-guide.zip"; Expand-Archive "$d\python-style-guide.zip" -DestinationPath $d -Force; ri "$d\python-style-guide.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して python-style-guide.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → python-style-guide フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
5

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Python スタイルガイド

Google's Python Style Guide に基づいた、クリーンで保守しやすい Python コードを書くための包括的なガイドラインです。

コアとなる理念

一貫性を保つこと。 周囲のコードのスタイルに合わせましょう。これらのガイドラインをデフォルトとして使用しますが、常に既存のコードとの一貫性を優先してください。

言語規則

インポート

import 文は、個々のクラスや関数ではなく、パッケージとモジュールのみに使用します。

良い例:

from doctor.who import jodie
import sound_effects.utils

悪い例:

from sound_effects.utils import EffectsRegistry  # クラスを直接インポートしないでください

インポートのフォーマット

  • インポートをグループ化する: 標準ライブラリ、サードパーティ、アプリケーション固有
  • 各グループ内でアルファベット順に並べる
  • 絶対インポートを使用する (相対インポートではない)
  • 1行に1つのインポート (ただし、typing または collections.abc からの複数のアイテムは除く)
# Standard library
import os
import sys

# Third-party
import numpy as np
import tensorflow as tf

# Application-specific
from myproject.backend import api_utils

例外

例外を適切に使用してください。ベアな except: 句でエラーを抑制しないでください。

良い例:

try:
    result = risky_operation()
except ValueError as e:
    logging.error(f"Invalid value: {e}")
    raise

悪い例:

try:
    result = risky_operation()
except:  # 広すぎるため、バグを隠してしまう
    pass

型アノテーション

すべての関数シグネチャにアノテーションを付けます。型アノテーションはコードの可読性を向上させ、エラーを早期に検出します。

一般的なルール:

  • すべてのパブリック API にアノテーションを付ける
  • typing.List などの代わりに、組み込み型 (list, dict, set) を使用する (Python 3.9 以降)
  • typing シンボルを直接インポートする: from typing import Any, Union
  • type(None) または NoneType の代わりに None を使用する
def fetch_data(url: str, timeout: int = 30) -> dict[str, Any]:
    """URL からデータを取得します。"""
    ...

def process_items(items: list[str]) -> None:
    """アイテムのリストを処理します。"""
    ...

デフォルト引数の値

関数定義で可変オブジェクトをデフォルト値として使用しないでください。

良い例:

def foo(a: int, b: list[int] | None = None) -> None:
    if b is None:
        b = []

悪い例:

def foo(a: int, b: list[int] = []) -> None:  # 可変のデフォルト - 間違い!
    b.append(a)

True/False の評価

可能な限り、暗黙的な false を使用してください。空のシーケンス、None、および 0 は、ブールコンテキストでは false になります。

良い例:

if not users:  # 推奨
if not some_dict:
if value:

悪い例:

if len(users) == 0:  # 冗長
if users == []:
if value == True:  # True/False と明示的に比較しないでください

内包表記とジェネレータ

単純なケースでは、内包表記とジェネレータを使用してください。可読性を保ってください。

良い例:

result = [x for x in data if x > 0]
squares = (x**2 for x in range(10))

悪い例:

# 複雑すぎる
result = [
    x.strip().lower() for x in data 
    if x and len(x) > 5 and not x.startswith('#')
    for y in x.split(',') if y
]  # 代わりに通常のループを使用してください

Lambda 関数

Lambda はワンライナーのみに使用してください。複雑な場合は、適切な関数を定義してください。

良い例:

sorted(data, key=lambda x: x.timestamp)

許容できるが、名前付き関数を推奨:

def get_timestamp(item):
    return item.timestamp

sorted(data, key=get_timestamp)

スタイル規則

行の長さ

最大行の長さ: 80 文字。インポート、URL、および分割できない長い文字列は例外として許可されます。

インデント

インデントレベルごとに 4 つのスペースを使用します。タブは絶対に使用しないでください。

ぶら下げインデントの場合は、ラップされた要素を垂直に揃えるか、4 スペースのぶら下げインデントを使用します。

# 開始デリミタに揃える
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# ぶら下げインデント (4 スペース)
foo = long_function_name(
    var_one, var_two, var_three,
    var_four)

空行

  • トップレベルの定義の間には 2 つの空行
  • メソッド定義の間には 1 つの空行
  • 関数内では、論理的なセクションを示すために空行を控えめに使用する

命名規則

タイプ 規則
パッケージ/モジュール lower_with_under my_module.py
クラス CapWords MyClass
関数/メソッド lower_with_under() my_function()
定数 CAPS_WITH_UNDER MAX_SIZE
変数 lower_with_under my_var
プライベート _leading_underscore _private_var

避けるべきこと:

  • カウンター/イテレータ (i, j, k) を除く、1 文字の名前
  • どの名前にもダッシュを使用しない
  • __double_leading_and_trailing_underscore__ (Python 用に予約済み)

コメントとドキュメンテーション文字列

ドキュメンテーション文字列の形式

すべてのパブリックモジュール、関数、クラス、およびメソッドに Google スタイルのドキュメンテーション文字列を使用します。

関数のドキュメンテーション文字列:

def fetch_smalltable_rows(
    table_handle: smalltable.Table,
    keys: Sequence[bytes | str],
    require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
    """Smalltable から行をフェッチします。

    table_handle で表される Table インスタンスから、指定されたキーに関連する行を取得します。
    文字列キーは UTF-8 でエンコードされます。

    Args:
        table_handle: 開いている smalltable.Table インスタンス。
        keys: フェッチする各テーブル行のキーを表す文字列のシーケンス。
            文字列キーは UTF-8 でエンコードされます。
        require_all_keys: True の場合、キーが見つからない場合は ValueError を発生させます。

    Returns:
        フェッチされた対応するテーブル行データへのキーのマッピングの dict。
        各行は文字列のタプルとして表されます。

    Raises:
        IOError: smalltable へのアクセス中にエラーが発生しました。
        ValueError: キーが見つからず、require_all_keys が True です。
    """
    ...

クラスのドキュメンテーション文字列:


class SampleClass:
    """クラスの概要をここに記述します。

    より長いクラス情報...
    より長いクラス情報...

    Attributes:
        likes_spam: SPAM が好きかどうかを示すブール値。


(原文はここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Python Style Guide

Comprehensive guidelines for writing clean, maintainable Python code based on Google's Python Style Guide.

Core Philosophy

BE CONSISTENT. Match the style of the code around you. Use these guidelines as defaults, but always prioritize consistency with existing code.

Language Rules

Imports

Use import statements for packages and modules only, not for individual classes or functions.

Yes:

from doctor.who import jodie
import sound_effects.utils

No:

from sound_effects.utils import EffectsRegistry  # Don't import classes directly

Import Formatting

  • Group imports: standard library, third-party, application-specific
  • Alphabetize within each group
  • Use absolute imports (not relative imports)
  • One import per line (except for multiple items from typing or collections.abc)
# Standard library
import os
import sys

# Third-party
import numpy as np
import tensorflow as tf

# Application-specific
from myproject.backend import api_utils

Exceptions

Use exceptions appropriately. Do not suppress errors with bare except: clauses.

Yes:

try:
    result = risky_operation()
except ValueError as e:
    logging.error(f"Invalid value: {e}")
    raise

No:

try:
    result = risky_operation()
except:  # Too broad, hides bugs
    pass

Type Annotations

Annotate all function signatures. Type annotations improve code readability and catch errors early.

General rules:

  • Annotate all public APIs
  • Use built-in types (list, dict, set) instead of typing.List, etc. (Python 3.9+)
  • Import typing symbols directly: from typing import Any, Union
  • Use None instead of type(None) or NoneType
def fetch_data(url: str, timeout: int = 30) -> dict[str, Any]:
    """Fetch data from URL."""
    ...

def process_items(items: list[str]) -> None:
    """Process a list of items."""
    ...

Default Argument Values

Never use mutable objects as default values in function definitions.

Yes:

def foo(a: int, b: list[int] | None = None) -> None:
    if b is None:
        b = []

No:

def foo(a: int, b: list[int] = []) -> None:  # Mutable default - WRONG!
    b.append(a)

True/False Evaluations

Use implicit false where possible. Empty sequences, None, and 0 are false in boolean contexts.

Yes:

if not users:  # Preferred
if not some_dict:
if value:

No:

if len(users) == 0:  # Verbose
if users == []:
if value == True:  # Never compare to True/False explicitly

Comprehensions & Generators

Use comprehensions and generators for simple cases. Keep them readable.

Yes:

result = [x for x in data if x > 0]
squares = (x**2 for x in range(10))

No:

# Too complex
result = [
    x.strip().lower() for x in data 
    if x and len(x) > 5 and not x.startswith('#')
    for y in x.split(',') if y
]  # Use a regular loop instead

Lambda Functions

Use lambdas for one-liners only. For anything complex, define a proper function.

Yes:

sorted(data, key=lambda x: x.timestamp)

Acceptable but prefer named function:

def get_timestamp(item):
    return item.timestamp

sorted(data, key=get_timestamp)

Style Rules

Line Length

Maximum line length: 80 characters. Exceptions allowed for imports, URLs, and long strings that can't be broken.

Indentation

Use 4 spaces per indentation level. Never use tabs.

For hanging indents, align wrapped elements vertically or use 4-space hanging indent:

# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Hanging indent (4 spaces)
foo = long_function_name(
    var_one, var_two, var_three,
    var_four)

Blank Lines

  • Two blank lines between top-level definitions
  • One blank line between method definitions
  • Use blank lines sparingly within functions to show logical sections

Naming Conventions

Type Convention Examples
Packages/Modules lower_with_under my_module.py
Classes CapWords MyClass
Functions/Methods lower_with_under() my_function()
Constants CAPS_WITH_UNDER MAX_SIZE
Variables lower_with_under my_var
Private _leading_underscore _private_var

Avoid:

  • Single character names except for counters/iterators (i, j, k)
  • Dashes in any name
  • __double_leading_and_trailing_underscore__ (reserved for Python)

Comments and Docstrings

Docstring Format

Use Google-style docstrings for all public modules, functions, classes, and methods.

Function docstring:

def fetch_smalltable_rows(
    table_handle: smalltable.Table,
    keys: Sequence[bytes | str],
    require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
    """Fetches rows from a Smalltable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by table_handle. String keys will be UTF-8 encoded.

    Args:
        table_handle: An open smalltable.Table instance.
        keys: A sequence of strings representing the key of each table
            row to fetch. String keys will be UTF-8 encoded.
        require_all_keys: If True, raise ValueError if any key is missing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings.

    Raises:
        IOError: An error occurred accessing the smalltable.
        ValueError: A key is missing and require_all_keys is True.
    """
    ...

Class docstring:

class SampleClass:
    """Summary of class here.

    Longer class information...
    Longer class information...

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam: bool = False):
        """Initializes the instance based on spam preference.

        Args:
            likes_spam: Defines if instance exhibits this preference.
        """
        self.likes_spam = likes_spam
        self.eggs = 0

Block and Inline Comments

  • Use complete sentences with proper capitalization
  • Block comments indent to the same level as the code
  • Inline comments should be separated by at least 2 spaces
  • Use inline comments sparingly
# Block comment explaining the following code.
# Can span multiple lines.
x = x + 1  # Inline comment (use sparingly)

Strings

Use f-strings for formatting (Python 3.6+).

Yes:

x = f"name: {name}; score: {score}"

Acceptable:

x = "name: %s; score: %d" % (name, score)
x = "name: {}; score: {}".format(name, score)

No:

x = "name: " + name + "; score: " + str(score)  # Avoid + for formatting

Logging

Use % formatting for logging, not f-strings (allows lazy evaluation):

logging.info("Request from %s resulted in %d", ip_address, status_code)

Files and Resources

Always use context managers (with statements) for file operations:

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

Statements

Generally avoid multiple statements on one line.

Yes:

if foo:
    bar()

No:

if foo: bar()  # Avoid

Main

For executable scripts, use:

def main():
    ...

if __name__ == "__main__":
    main()

Function Length

Keep functions focused and reasonably sized. If a function exceeds about 40 lines, consider splitting it unless it remains very readable.

Type Annotation Details

Forward Declarations

Use string quotes for forward references:

class MyClass:
    def method(self) -> "MyClass":
        return self

Type Aliases

Create aliases for complex types:

from typing import TypeAlias

ConnectionOptions: TypeAlias = dict[str, str]
Address: TypeAlias = tuple[str, int]
Server: TypeAlias = tuple[Address, ConnectionOptions]

TypeVars

Use descriptive names for TypeVars:

from typing import TypeVar

_T = TypeVar("_T")  # Good: private, unconstrained
AddableType = TypeVar("AddableType", int, float, str)  # Good: descriptive

Generics

Always specify type parameters for generic types:

Yes:

def get_names(employee_ids: list[int]) -> dict[int, str]:
    ...

No:

def get_names(employee_ids: list) -> dict:  # Missing type parameters
    ...

Imports for Typing

Import typing symbols directly:

from collections.abc import Mapping, Sequence
from typing import Any, Union

# Use built-in types for containers (Python 3.9+)
def foo(items: list[str]) -> dict[str, int]:
    ...

Common Patterns

Properties

Use properties for simple attribute access:

class Square:
    def __init__(self, side: float):
        self._side = side

    @property
    def area(self) -> float:
        return self._side ** 2

Conditional Expressions

Use ternary operators for simple conditions:

x = "yes" if condition else "no"

Context Managers

Create custom context managers when appropriate:

from contextlib import contextmanager

@contextmanager
def managed_resource(*args, **kwargs):
    resource = acquire_resource(*args, **kwargs)
    try:
        yield resource
    finally:
        release_resource(resource)

Linting

Run pylint on all Python code. Suppress warnings only when necessary with clear explanations:

dict = 'something'  # pylint: disable=redefined-builtin

Summary

When writing Python code:

  1. Use type annotations for all functions
  2. Follow naming conventions consistently
  3. Write clear docstrings for all public APIs
  4. Keep functions focused and reasonably sized
  5. Use comprehensions for simple cases
  6. Prefer implicit false in boolean contexts
  7. Use f-strings for formatting
  8. Always use context managers for resources
  9. Run pylint and fix issues
  10. BE CONSISTENT with existing code

Additional Resources

For detailed reference on specific topics, see:

  • references/advanced_types.md - Advanced type annotation patterns including Protocol, TypedDict, Literal, ParamSpec, and more
  • references/antipatterns.md - Common Python mistakes and their fixes
  • references/docstring_examples.md - Comprehensive docstring examples for all Python constructs

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。