python
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWhat I do
我的功能
I help you write Python code that follows professional style guide conventions. This includes:
- Enforcing naming conventions (snake_case, PascalCase, UPPER_CASE)
- Applying proper docstring formatting (module, class, function, method docstrings)
- Managing imports correctly (full package paths, proper ordering)
- Implementing type annotations following best practices
- Following line length and indentation rules
- Using proper exception handling patterns
- Writing clean, readable code that matches professional standards
我可以帮助你编写符合专业风格指南规范的Python代码,具体包括:
- 强制执行命名规范(snake_case、PascalCase、UPPER_CASE)
- 应用正确的文档字符串(docstring)格式化(模块、类、函数、方法的文档字符串)
- 正确管理导入(完整包路径、合理排序)
- 遵循最佳实践实现类型注解
- 遵守行长度和缩进规则
- 使用正确的异常处理模式
- 编写符合专业标准的简洁、可读代码
When to use me
适用场景
Use this skill when:
- Writing new Python code that should follow style guide conventions
- Refactoring existing Python code to match best practices
- Reviewing Python code for style compliance
- Adding documentation to Python modules, classes, or functions
- Setting up type hints for Python code
- Organizing imports in Python files
在以下场景可以使用本功能:
- 编写需要遵循风格指南规范的新Python代码时
- 重构现有Python代码以匹配最佳实践时
- 检查Python代码的风格合规性时
- 为Python模块、类或函数添加文档时
- 为Python代码设置类型提示时
- 整理Python文件中的导入语句时
Key style rules I enforce
我强制执行的核心风格规则
Naming Conventions
命名规范
- Modules: (lowercase with underscores)
module_name.py - Packages: (lowercase, no underscores preferred)
package_name - Classes: (PascalCase)
ClassName - Functions: (lowercase with underscores)
function_name() - Variables: (lowercase with underscores)
variable_name - Constants: (uppercase with underscores)
CONSTANT_NAME - Private attributes: (leading underscore)
_private_var - Internal globals: (leading underscore)
_internal_global - Strongly private attributes: (double leading underscore for name mangling)
__secret_var
Important: For strongly private attributes that should be protected via name mangling, always use double underscore prefix:
python
class MyClass:
def __init__(self):
# Public attribute
self.public_var: str = "visible"
# Protected attribute (convention only)
self._protected_var: str = "use with care"
# Private attribute (name mangled to _MyClass__secret)
self.__secret: str = "truly private"- 模块:(小写加下划线)
module_name.py - 包:(小写,优先不使用下划线)
package_name - 类:(PascalCase)
ClassName - 函数:(小写加下划线)
function_name() - 变量:(小写加下划线)
variable_name - 常量:(大写加下划线)
CONSTANT_NAME - 私有属性:(前置单个下划线)
_private_var - 内部全局变量:(前置单个下划线)
_internal_global - 强私有属性:(前置双下划线以实现名称修饰)
__secret_var
重要提示:对于需要通过名称修饰保护的强私有属性,始终使用双下划线前缀:
python
class MyClass:
def __init__(self):
# 公共属性
self.public_var: str = "visible"
# 受保护属性(仅为约定)
self._protected_var: str = "use with care"
# 私有属性(名称修饰为 _MyClass__secret)
self.__secret: str = "truly private"Imports
导入规范
Use full package paths:
python
undefined使用完整包路径:
python
undefinedGood
规范写法
from absl import flags
from doctor.who import jodie
from absl import flags
from doctor.who import jodie
Bad
不规范写法
import jodie # Ambiguous
Import order:
1. Standard library imports
2. Third-party imports
3. Local application importsimport jodie # 模糊不清
导入顺序:
1. 标准库导入
2. 第三方库导入
3. 本地应用代码导入Docstrings
文档字符串(Docstring)
Always use triple-quoted strings format.
"""Function docstring template:
python
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 only rows with values set for all keys will be
returned.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}
Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).
Raises:
IOError: An error occurred accessing the smalltable.
"""Class docstring template:
python
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 = 0Module docstring template:
python
"""A one-line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
foo = ClassFoo()
bar = foo.function_bar()
"""始终使用三引号格式。
"""函数文档字符串模板:
python
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 only rows with values set for all keys will be
returned.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}
Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).
Raises:
IOError: An error occurred accessing the smalltable.
"""类文档字符串模板:
python
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模块文档字符串模板:
python
"""A one-line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
foo = ClassFoo()
bar = foo.function_bar()
"""Type Annotations
类型注解
Always add type hints to function signatures:
python
def func(a: int) -> list[int]:
return [a * 2]始终为函数签名添加类型提示:
python
def func(a: int) -> list[int]:
return [a * 2]For variables when type isn't obvious
当变量类型不明确时添加注解
a: SomeType = some_func()
a: SomeType = some_func()
Use modern syntax (Python 3.10+)
使用现代语法(Python 3.10+)
def process(data: str | None = None) -> dict[str, int]:
pass
**Important**: Use capitalized type hints from `typing` module instead of built-in lowercase types:
```python
from typing import Dict, List, Set, Tuple, Optionaldef process(data: str | None = None) -> dict[str, int]:
pass
**重要提示**:使用`typing`模块中的大写类型提示,而非内置的小写类型:
```python
from typing import Dict, List, Set, Tuple, OptionalGood - using typing module
规范写法 - 使用typing模块
def process_users(users: List[str]) -> Dict[str, int]:
return {user: len(user) for user in users}
def get_config() -> Dict[str, List[int]]:
return {"ports": [8080, 8081]}
def process_users(users: List[str]) -> Dict[str, int]:
return {user: len(user) for user in users}
def get_config() -> Dict[str, List[int]]:
return {"ports": [8080, 8081]}
Good - with Optional
规范写法 - 使用Optional
def find_user(user_id: int) -> Optional[str]:
return None
def find_user(user_id: int) -> Optional[str]:
return None
Bad - using built-in lowercase types (avoid)
不规范写法 - 使用内置小写类型(避免)
def process_users(users: list[str]) -> dict[str, int]:
return {user: len(user) for user in users}
Note: While Python 3.9+ supports lowercase `list`, `dict`, etc., using the `typing` module variants (`List`, `Dict`) is preferred for consistency and broader compatibility.def process_users(users: list[str]) -> dict[str, int]:
return {user: len(user) for user in users}
注意:虽然Python 3.9+支持小写的`list`、`dict`等,但为了一致性和更广的兼容性,优先使用`typing`模块的变体(`List`、`Dict`)。Line Length and Formatting
行长度与格式化
- Maximum line length: 80 characters
- Use implicit line continuation with parentheses (not backslashes)
- Indent with 4 spaces (never tabs)
- Two blank lines between top-level definitions
- One blank line between method definitions
python
undefined- 最大行长度:80个字符
- 使用括号实现隐式换行(而非反斜杠)
- 使用4个空格缩进(绝不使用制表符)
- 顶级定义之间保留两个空行
- 方法定义之间保留一个空行
python
undefinedGood
规范写法
foo_bar(
self, width, height, color='black', design=None, x='foo',
emphasis=None, highlight=0
)
foo_bar(
self, width, height, color='black', design=None, x='foo',
emphasis=None, highlight=0
)
Good
规范写法
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong'):
pass
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong'):
pass
Bad - backslash continuation
不规范写法 - 反斜杠换行
if width == 0 and height == 0 and
color == 'red' and emphasis == 'strong': pass
color == 'red' and emphasis == 'strong': pass
undefinedif width == 0 and height == 0 and
color == 'red' and emphasis == 'strong': pass
color == 'red' and emphasis == 'strong': pass
undefinedException Handling
异常处理
python
undefinedpython
undefinedGood
规范写法
def connect_to_next_port(self, minimum: int) -> int:
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
port = self._find_next_port(minimum)
if port is None:
raise ConnectionError(
f'Could not connect to service on port {minimum} or higher.')
return portundefineddef connect_to_next_port(self, minimum: int) -> int:
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
port = self._find_next_port(minimum)
if port is None:
raise ConnectionError(
f'Could not connect to service on port {minimum} or higher.')
return portundefinedDefault Arguments
默认参数
Never use mutable objects as default values:
python
undefined绝不要使用可变对象作为默认值:
python
undefinedGood
规范写法
def foo(a, b: list[int] | None = None):
if b is None:
b = []
def foo(a, b: list[int] | None = None):
if b is None:
b = []
Bad
不规范写法
def foo(a, b: list[int] = []):
pass
undefineddef foo(a, b: list[int] = []):
pass
undefinedBoolean Evaluations
布尔值判断
Use implicit false when possible:
python
undefined尽可能使用隐式假值判断:
python
undefinedGood
规范写法
if not users:
print('no users')
if foo:
bar()
if not users:
print('no users')
if foo:
bar()
Check for None explicitly
显式检查None
if x is None:
pass
if x is None:
pass
Bad
不规范写法
if len(users) == 0:
print('no users')
if foo != []:
bar()
undefinedif len(users) == 0:
print('no users')
if foo != []:
bar()
undefinedComprehensions
推导式
Keep them simple - optimize for readability:
python
undefined保持简洁——优先考虑可读性:
python
undefinedGood
规范写法
result = [mapping_expr for value in iterable if filter_expr]
result = [mapping_expr for value in iterable if filter_expr]
Good
规范写法
result = [
is_valid(metric={'key': value})
for value in interesting_iterable
if a_longer_filter_expression(value)
]
result = [
is_valid(metric={'key': value})
for value in interesting_iterable
if a_longer_filter_expression(value)
]
Bad - multiple for clauses
不规范写法 - 多个for子句
result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
undefinedresult = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
undefinedLoop Variables
循环变量
Important: Always use underscore prefix for loop variables when you don't use the variable itself:
python
undefined重要提示:当你不使用循环变量本身时,始终为其添加下划线前缀:
python
undefinedGood - using underscore when variable is not used
规范写法 - 不使用变量时添加下划线
for _user in users:
print("Processing a user")
send_notification()
for _item in items:
count += 1
for _user in users:
print("Processing a user")
send_notification()
for _item in items:
count += 1
Good - using the variable
规范写法 - 使用变量时
for user in users:
print(f"Processing {user.name}")
user.process()
for user in users:
print(f"Processing {user.name}")
user.process()
Bad - not using underscore when variable is unused
不规范写法 - 未使用变量时未添加下划线
for user in users: # 'user' is never referenced
print("Processing a user")
This convention makes it immediately clear that the loop variable is intentionally unused.for user in users: # 'user'从未被引用
print("Processing a user")
此约定可以让他人立刻明确该循环变量是有意不被使用的。Linting
代码检查(Linting)
- Run on all code
pylint - Suppress warnings with inline comments when appropriate:
python
def do_PUT(self): # WSGI name, so pylint: disable=invalid-name
pass- 对所有代码运行
pylint - 在合适的情况下使用行内注释抑制警告:
python
def do_PUT(self): # WSGI名称,因此添加 pylint: disable=invalid-name
passThe Zen of Python
Python之禅
Follow these fundamental principles from PEP 20 (The Zen of Python):
- Beautiful is better than ugly - Write elegant, readable code
- Explicit is better than implicit - Be clear about what your code does
- Simple is better than complex - Favor straightforward solutions
- Complex is better than complicated - When complexity is needed, keep it organized
- Flat is better than nested - Avoid deep nesting when possible
- Sparse is better than dense - Use whitespace for readability
- Readability counts - Code is read more often than written
- Special cases aren't special enough to break the rules - Consistency matters
- Although practicality beats purity - Pragmatism over dogmatism when needed
- Errors should never pass silently - Handle exceptions explicitly
- In the face of ambiguity, refuse the temptation to guess - Be explicit
- There should be one-- and preferably only one --obvious way to do it - Favor the idiomatic approach
- Now is better than never - Don't overthink, start coding
- Although never is often better than right now - But plan before rushing
- If the implementation is hard to explain, it's a bad idea - Simplicity test
- If the implementation is easy to explain, it may be a good idea - Clarity indicator
- Namespaces are one honking great idea - Use them to organize code
Access these at any time by running:
python
import thisKey principles to remember:
- Explicit > Implicit
- Simple > Complex
- Readability counts
- One obvious way to do things
遵循PEP 20(Python之禅)中的基本原则:
- 优美胜于丑陋 - 编写优雅、可读的代码
- 明了胜于晦涩 - 清晰展示代码的功能
- 简洁胜于复杂 - 优先选择直接的解决方案
- 复杂胜于凌乱 - 当需要复杂实现时,保持结构清晰
- 扁平胜于嵌套 - 尽可能避免深层嵌套
- 间隔胜于紧凑 - 使用空白提升可读性
- 可读性很重要 - 代码被阅读的次数远多于编写次数
- 即便特例,也不可违背这些规则 - 一致性至关重要
- 尽管实用性会打败纯粹性 - 必要时优先务实而非教条
- 错误绝不能悄悄忽略 - 显式处理异常
- 面对歧义,拒绝猜测 - 保持明确
- 任何问题应有一种,且最好只有一种,显而易见的解决方法 - 优先使用惯用写法
- 动手做,胜于不做 - 不要过度思考,开始编码
- 不假思索就动手,不如不做 - 但在匆忙前先做好规划
- 如果实现难以解释,那它一定是个坏主意 - 简洁性测试
- 如果实现易于解释,那它可能是个好主意 - 清晰性指标
- 命名空间是个绝妙的主意 - 使用它们来组织代码
你可以随时通过运行以下代码查看这些原则:
python
import this需要牢记的核心原则:
- 显式 > 隐式
- 简洁 > 复杂
- 可读性至关重要
- 问题应有一种显而易见的解决方法
How I work
我的工作流程
When you ask me to help with Python code, I will:
- Analyze the code for style violations
- Suggest specific improvements citing relevant style rules
- Rewrite code sections to match professional style
- Add proper docstrings following standard format
- Format imports, line lengths, and indentation correctly
- Apply type annotations where missing or incorrect
I prioritize readability and maintainability over brevity. When there's ambiguity, I'll ask clarifying questions about your specific use case.
当你请求我协助处理Python代码时,我会:
- 分析代码中的风格违规问题
- 建议具体的改进方案,并引用相关的风格规则
- 重写代码片段以匹配专业风格
- 添加符合标准格式的正确文档字符串
- 格式化导入语句、行长度和缩进
- 补充缺失或不正确的类型注解
我优先考虑可读性和可维护性而非简洁性。当存在歧义时,我会询问关于你具体使用场景的澄清问题。
References
参考资料
- Full style guide: https://google.github.io/styleguide/pyguide.html
- PEP 8 (Python's general style guide): https://peps.python.org/pep-0008/
- PEP 257 (Docstring conventions): https://peps.python.org/pep-0257/
- Type hints (PEP 484): https://peps.python.org/pep-0484/
- 完整风格指南:https://google.github.io/styleguide/pyguide.html
- PEP 8(Python通用风格指南):https://peps.python.org/pep-0008/
- PEP 257(文档字符串规范):https://peps.python.org/pep-0257/
- 类型提示(PEP 484):https://peps.python.org/pep-0484/