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.
- License 许可
- CC-BY-4.0
- 最近更新
- 2026-11-15
- Stars
- ★ 6
- Forks
- 0
01 前言 Front Matter
- name
- python-style-guide
- license
- Complete terms in LICENSE.txt
- description
- 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.
02 资源文件 2
- 许可证LICENSE18.2 KB
- 参考文档skill-report.json90.7 KB
03 SKILL.md 正文
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
typingorcollections.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 oftyping.List, etc. (Python 3.9+) - Import typing symbols directly:
from typing import Any, Union - Use
Noneinstead oftype(None)orNoneType
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:
- Use type annotations for all functions
- Follow naming conventions consistently
- Write clear docstrings for all public APIs
- Keep functions focused and reasonably sized
- Use comprehensions for simple cases
- Prefer implicit false in boolean contexts
- Use f-strings for formatting
- Always use context managers for resources
- Run pylint and fix issues
- 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
04 同仓库更多 Skills
serpmaven
Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.
revnu-landing-page-audit
Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: "audit my landing page", "why isn't this page converting", "review my homepage", "my ads get clicks but no signups", "people bounce from the pricing page", "CRO review", "improve conversion rate", "is my hero section clear", "roast my landing page", "rewrite my headline", "what's wrong with this page", "landing page feedback", "make the signup page convert better". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.
revnu-growth-context
Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents/revnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says "set up our marketing context", "who is our ideal customer", "write our ICP", "describe the product for marketing", "positioning doc", "what's our brand voice", "remember this about our customers", "log what we tried", "what have we learned from marketing", "we changed pricing, update the context", "update our growth notes", "summarize the business for the agent", "import my product-marketing.md", "start a growth doc", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.
revnu-get-listed
Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: "best X" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says "get us listed", "which directories should we submit to", "how do we get into best-of lists", "why does ChatGPT recommend competitors and not us", "get mentioned in AI answers", "submit to awesome lists", "get on G2", "where are our competitors listed", "pitch listicle authors", "find backlink opportunities", "launch directories", "get into roundups", "Product Hunt alternatives", "where should we be listed", "get cited by Perplexity". Never submits, pays or posts without a yes. Works without a Revnu account.
revnu-ai-readiness-audit
Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks "is my site ready for AI search", "audit my site for AI answers", "AEO audit", "GEO audit", "why doesn't ChatGPT quote our pricing", "make our pages citable by AI", "do I need llms.txt", "does schema help with ChatGPT", "check our structured data", "is our content visible without JavaScript", "AI SEO audit", "optimize our homepage for AI answers", "LLM SEO check", "why does AI get our product wrong", "fix our site for AI Overviews". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.
proxy-troubleshooting
Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.