python
БесплатноБез исполняемых скриптовНе проверенApply when writing Python code. Type hints, error handling, mutable defaults, async patterns, and packaging conventions.
Об этом скилле
Sub-Skill: Python Best Practices
Purpose: Prevents the Python-specific mistakes LLMs make on autopilot — mutable defaults, bare excepts, missing guards, and subtle performance traps that pass review but break in production.
Rule classification
- MUST — load-bearing. Violating causes bugs, security issues, or invisible failures. Never break.
- SHOULD — default behavior. Deviation needs a documented reason in the code or PR.
- AVOID — usually wrong; documented exception inline where needed.
Where these rules don't strictly apply: test fixtures, generated code, throwaway scripts, REPL exploration, and tutorial snippets may legitimately differ. The rules below apply to production code paths and reusable libraries.
Rules
Type Hints
SHOULD: Annotate function signatures with types.
def process(data)tells callers nothing. Usedef process(data: list[str]) -> dict[str, int]:. Return typeNoneshould be explicit too. Exception: lambdas and short generator helpers in private scope.SHOULD: Use built-in lowercase generics for Python 3.9+.
list[str],dict[str, int],tuple[int, ...]rather thanList,Dict,Tuplefromtyping.MUST: Use
Optional[X]orX | Nonefor nullable parameters, never a bare default ofNonewithout a type annotation.def find(id: int) -> User | None:notdef find(id):.AVOID:
Anyas a shortcut. If the type is genuinely unknown, document why with a comment.Anysilences the type checker and hides bugs. Exception: third-party libraries without stubs and explicit dynamic-data boundaries (e.g. JSON decode at the API edge).
Error Handling
MUST: Never use bare
except:. It catchesSystemExit,KeyboardInterrupt, andGeneratorExit. Always catchexcept Exception:at minimum, or a specific exception class.# Wrong try: risky() except: pass # Correct try: risky() except ValueError as e: logger.warning("Invalid value: %s", e)MUST: Never silently swallow exceptions with
pass. At minimum log the error. Silent failures produce ghost bugs that are impossible to trace.SHOULD: Raise with context when re-raising. Use
raise NewError("msg") from original_errorto preserve the traceback chain, notraise NewError("msg")alone.
Common Pitfalls
MUST: Never use mutable default arguments. Python evaluates defaults once at function definition, not per call. The list or dict is shared across all calls.
# Wrong — items accumulates across calls def append_item(val, items=[]): items.append(val) return items # Correct def append_item(val, items=None): if items is None: items = [] items.append(val) return itemsMUST: Guard script entry points with
if __name__ == "__main__":. Without it, importing the module executes top-level code, breaking tests and imports.MUST: Use
withfor file handles, sockets, and locks. Never open a file without a context manager.f = open(...)withoutwithleaks handles on exceptions.# Wrong f = open("data.txt") data = f.read() f.close() # Correct with open("data.txt") as f: data = f.read()AVOID: String concatenation in loops. Each
+=on a string creates a new object. Collect into a list and call"".join(parts)at the end.# Wrong — O(n^2) memory result = "" for word in words: result += word + " " # Correct result = " ".join(words)SHOULD: Use f-strings for string interpolation in Python 3.6+. Avoid
%formatting or"Hello " + name. F-strings are faster, safer, and readable.# Avoid msg = "User %s has %d items" % (name, count) # Prefer msg = f"User {name} has {count} items"AVOID:
dict()constructor when a literal suffices.{}is faster and more idiomatic.dict(key=value)is only justified when keys are dynamic or come from variables.
Performance
SHOULD: Use list comprehensions or generator expressions instead of
map/filterwithlambda. Comprehensions are more readable and equally fast. Use generators when the full list is not needed at once.# Avoid result = list(map(lambda x: x * 2, items)) # Prefer result = [x * 2 for x in items] # For large data, use a generator total = sum(x * 2 for x in items)SHOULD: Use a
setfor membership lookups, not alist.x in listis O(n).x in setis O(1). Convert once, query many times.# Wrong for repeated lookups valid_ids = [1, 2, 3, ...] if user_id in valid_ids: # O(n) every call # Correct valid_ids = {1, 2, 3, ...}
Установить python в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл python?
Apply when writing Python code. Type hints, error handling, mutable defaults, async patterns, and packaging conventions.
Как установить скилл python?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл python запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic