python-advanced
БесплатноБез исполняемых скриптовНе проверенAdvanced Python 3.13 on Windows: typed package design, pyproject/src layout, asyncio and cancellation, threads vs processes, robust subprocesses, pytest…
от deepseekoracle323 установки в других каталогахОб этом скилле
Python Advanced
Reference interpreter: Python 3.13.5; use python or py -3.13. Use python-advanced for interpreter/venv basics; this skill is the design and failure-mode layer.
1. Project layout
project/
pyproject.toml
README.md
LICENSE
src/
package_name/
__init__.py
cli.py
core.py
tests/
test_core.py
.venv/
- Use a src layout; it prevents importing the working tree instead of the installed package.
- One project, one distribution name, one import package.
- Do not commit
.venv,__pycache__,dist, or.egg-info. - Pin the interpreter in
requires-python.
2. pyproject template
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
[project]
name = "lygo-tool"
version = "0.1.0"
description = "Small typed tool"
readme = "README.md"
requires-python = ">=3.11"
license = "MIT"
dependencies = [
"httpx>=0.27",
"pydantic>=2.8",
]
[project.optional-dependencies]
dev = ["pytest>=8", "pytest-cov>=5", "ruff>=0.8", "mypy>=1.13"]
[project.scripts]
lygo-tool = "lygo_tool.cli:main"
[tool.ruff]
line-length = 100
target-version = "py311"
[tool.mypy]
strict = true
python_version = "3.11"
Build:
python -m pip install -U build
python -m build
The wheel goes to dist/; install with the same interpreter.
3. Typing that pays for itself
from __future__ import annotations
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Literal, Protocol, TypeAlias
Mode: TypeAlias = Literal["fast", "safe"]
@dataclass(frozen=True, slots=True)
class Job:
name: str
retries: int = 0
class Store(Protocol):
def put(self, key: str, value: bytes) -> None: ...
def get(self, key: str) -> bytes | None: ...
def total(xs: Iterable[int]) -> int:
return sum(xs)
def first(xs: Sequence[int]) -> int:
if not xs:
raise ValueError("empty")
return xs[0]
Rules:
Protocolfor interfaces you do not own.TypedDictfor JSON-like records;dataclassfor domain objects.Literalfor finite modes;Annotatedfor metadata.- Avoid
Any; isolate untyped third-party boundaries in one adapter. from __future__ import annotationsmakes annotations strings; good for startup and forward refs.- Run
mypy --strictorpyright; fix errors at boundaries first.
4. asyncio
import asyncio
async def fetch(i: int) -> int:
await asyncio.sleep(0.1)
return i * 2
async def main() -> None:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(i)) for i in range(5)]
print([t.result() for t in tasks])
asyncio.run(main())
asyncio.run()is the entrypoint; do not call it inside a running loop.- Use
TaskGroup(3.11+) for structured concurrency; it cancels siblings on failure. - Wrap network calls in
asyncio.timeout(10). - Use
asyncio.to_thread()for blocking libraries. - Do not call
time.sleep,requests, or CPU-heavy code directly in a coroutine. - Cancel tasks deliberately and await cancellation.
async withfor clients/sessions; close them.
5. Threads vs processes
| Workload | Choice |
|---|---|
| Network/file I/O, waiting | threads or asyncio |
| CPU-bound pure Python | ProcessPoolExecutor |
| C library releasing the GIL | threads may help |
| Shared mutable state | avoid; queue/message passing |
| Windows multiprocessing | guard with if __name__ == "__main__": |
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
with ThreadPoolExecutor(max_workers=8) as ex:
results = list(ex.map(fetch_url, urls))
with ProcessPoolExecutor() as ex:
results = list(ex.map(cpu_job, items))
- Windows uses spawn; the entry module is re-imported. Guard the entrypoint.
- Do not pass unpicklable objects to processes.
- Threads share memory; processes do not.
- The GIL limits pure-Python CPU parallelism; use processes or native code.
6. Robust subprocesses
import subprocess, sys
def run(cmd: list[str], timeout: int = 30) -> subprocess.CompletedProcess[str]:
return subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
check=False,
shell=False,
)
Rules:
shell=Falseunless you need shell syntax; then never interpolate untrusted input.- Pass a list, not a string with spaces.
- Set
timeout; handlesubprocess.TimeoutExpired. check=TrueraisesCalledProcessError;check=Falsemeans inspectreturncode.- Use
encoding+errorson Windows; console code pages are not UTF-8. - Capture both streams; a full pipe can deadlock if the child writes a lot.
- For long-lived children, u
Установить python-advanced в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл python-advanced?
Advanced Python 3.13 on Windows: typed package design, pyproject/src layout, asyncio and cancellation, threads vs processes, robust subprocesses, pytest, ruff/mypy, profiling, C/PyO3 extensions, and Windows-specific failures. Use after the python-advanced basics when code must be typed, packaged, concurrent, testable, or fast.
Как установить скилл python-advanced?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл python-advanced запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic