USP
Unlike generic search, this plugin integrates directly with Claude Code to provide context-aware Python solutions by fetching battle-tested patterns from pythonsheets.com, ensuring functional and correct code.
Use cases
- 01Answering Python questions
- 02Python interview preparation
- 03Debugging Python code
- 04Optimizing Python performance
- 05Learning async patterns
Detected files (3)
skills/py/SKILL.mdskillShow content (3556 bytes)
--- name: py description: Comprehensive Python programming reference covering syntax, concurrency, networking, databases, ML/LLM development, and HPC. Use for: Python questions, Python interview preparation, debugging, performance optimization, async patterns, library examples, code review, best practices, MLOps workflows, distributed computing, security implementations, and any Python development tasks. --- # Python Cheat Sheets (/py) Help users write functional, correct Python code and answer Python questions by fetching proven patterns and examples from pythonsheets.com. ## How It Works When a user asks a Python question or wants to write a Python script: 1. Look up the relevant topic(s) in [Structure](references/structure.md) to find the matching URL(s) 2. **Always fetch** the URL(s) using WebFetch to get real examples and patterns from the site 3. Use the fetched content to: - **Write code**: Apply the patterns to produce functional, correct code that solves the user's task - **Answer questions**: Provide thorough explanations backed by the examples and information from the site 4. Follow the [Guidelines](references/guidelines.md) for code quality ## Key Principle **Functionality first, cleanliness second.** The code must work correctly and handle the task properly. Fetching from pythonsheets.com ensures solutions use battle-tested patterns rather than guessing. The site contains rich examples covering edge cases, common pitfalls, and practical usage that go beyond basic documentation. ## Coverage Areas **Interview Prep:** Curated Python interview questions grouped by topic (GIL, asyncio, decorators, MRO, generators, concurrency), each deep-linked to the section that answers it **Core:** Syntax, typing, OOP, functions, data structures, sets, heap, regex, unicode **System:** File I/O, datetime, OS interfaces **Concurrency:** Threading, multiprocessing, asyncio **Network:** Sockets, SSL/TLS, SSH, async I/O, packet sniffing **Database:** SQLAlchemy ORM, queries, transactions **Security:** Cryptography, TLS, vulnerabilities **Extensions:** C/C++ integration, pybind11, Cython **ML/LLM:** PyTorch, Megatron, distributed training, inference, serving, benchmarking **HPC:** Slurm, cluster computing, job scheduling, EFA monitoring, NCCL **Appendix:** Walrus operator, GDB debugging, disaggregated prefill/decode ## References - **[Structure](references/structure.md)** - Topic-to-URL map for fetching examples - **[Guidelines](references/guidelines.md)** - Code quality standards to apply after ensuring correctness ## Examples - "What should I review for a Python interview?" → Fetch https://www.pythonsheets.com/notes/interview/index.html and walk the reader through the topic groups - "Common Python interview questions on the GIL" → Fetch https://www.pythonsheets.com/notes/interview/index.html and then drill into https://www.pythonsheets.com/notes/concurrency/python-threading.html for detailed answers - "How does asyncio work?" → Fetch https://www.pythonsheets.com/notes/asyncio/python-asyncio-guide.html and explain with the site's examples - "Write a socket server" → Fetch https://www.pythonsheets.com/notes/network/python-socket-server.html, use the patterns to write a working server - "What's the walrus operator?" → Fetch https://www.pythonsheets.com/notes/appendix/python-walrus.html and explain with practical examples - "Set up Megatron distributed training" → Fetch https://www.pythonsheets.com/notes/llm/megatron.html, use the patterns to write a correct training scriptskills/readable-py/SKILL.mdskillShow content (9785 bytes)
--- name: readable-py description: Readable Python code rules inspired by The Art of Readable Code. Use when writing, reviewing, or refactoring Python code. Enforces short functions, flat control flow, clear naming, readable structure, and Pythonic idioms. --- # Readable Python Rules (/readable-py) Apply these rules when writing, reviewing, or refactoring Python code. Inspired by *The Art of Readable Code* by Dustin Boswell and Trevor Foucher. **Core principle: Code should be easy to understand.** The time it takes someone else (or future you) to understand the code is the ultimate metric. ## 1. Keep Functions Short and Focused - A function should do **one thing**. If you can describe what it does with "and", split it. - Aim for functions that fit on one screen (~15-25 lines). If it's longer, extract sub-tasks. - Each function should operate at a **single level of abstraction** — don't mix high-level logic with low-level details in the same function. ## 2. Flatten Control Flow — No Deep Nesting - **Never nest more than 2 levels deep.** If you have a loop inside a loop, or an `if` inside a loop inside an `if`, extract the inner block into a helper function with a descriptive name. - Use **early returns / guard clauses** to handle edge cases at the top, keeping the main logic flat. - Prefer `continue` or `break` to skip iterations rather than wrapping the body in a conditional. - Replace complex conditionals with well-named helper functions or variables that explain the intent. ``` # Bad: nested and hard to follow for user in users: if user.is_active: for order in user.orders: if order.is_pending: process(order) # Good: flat, each function name explains what it does active_users = get_active_users(users) for user in active_users: process_pending_orders(user.orders) ``` ## 3. Name Things Clearly - **Pack information into names.** Use specific, concrete words — `fetch_page` not `get`, `num_retries` not `n`. - **Avoid generic names** like `tmp`, `data`, `result`, `val`, `info`, `handle` — unless the scope is tiny (2-3 lines). - **Use names that can't be misconstrued.** If a range is inclusive, say `max_items` not `limit`. If a boolean, use `is_`, `has_`, `should_`, `can_` prefixes. - **Match the name length to the scope.** Short names for small scopes, descriptive names for wide scopes. - **Don't use abbreviations** unless they're universally understood (`num`, `max`, `min`, `err` are fine; `svc_mgr_cfg` is not). ## 4. Make Control Flow Easy to Follow - Put the **changing/interesting value on the left** side of comparisons: `if length > 10` not `if 10 < length`. - Order `if/else` blocks: **positive case first**, simpler case first, or the more interesting case first. - Minimize the number of variables the reader has to track. Reduce the **mental footprint** of each block. - Avoid the **ternary operator** for anything non-trivial — if it's not immediately obvious, use an `if/else`. ## 5. Break Down Giant Expressions - Use **explaining variables** to break complex expressions into named pieces. - Use **summary variables** to capture a long expression that's used more than once. - Apply **De Morgan's laws** to simplify negated boolean expressions. ``` # Bad if not (age >= 18 and has_id and not is_banned): deny() # Good is_eligible = age >= 18 and has_id and not is_banned if not is_eligible: deny() ``` ## 6. Extract Unrelated Subproblems - If a block of code is solving a **subproblem unrelated to the main goal** of the function, extract it. - The helper function should be **pure and self-contained** — it shouldn't need to know about the calling context. - This is the single most effective way to improve readability: separate *what* you're doing from *how*. ## 7. One Task at a Time - Each section of code should do **one task**. If a function is doing parsing AND validation AND transformation, split them into separate steps. - List the tasks a function does. If there's more than one, reorganize so each task is in its own block or function. ## 8. Reduce Variable Scope - **Declare variables close to where they're used.** Don't declare at the top of a function if it's only used 30 lines later. - **Minimize the "live time" of a variable** — the fewer lines between its assignment and last use, the easier it is to follow. - **Prefer write-once variables.** Variables that are assigned once and never modified are easier to reason about. - **Eliminate unnecessary variables.** If a variable is used only once and doesn't clarify anything, inline it. ## 9. No Magic Numbers or Strings - Replace **magic numbers and strings** with named constants: `if retries > MAX_RETRIES` not `if retries > 3`. - If a value has meaning, give it a name. The name documents the intent. - Group related constants together. ## 10. Fewer Function Arguments - Aim for **3 or fewer arguments** per function. More than that is a smell. - Group related arguments into an **object, dataclass, or named tuple**. - If a function needs many config-like options, pass a single config/options object. - Boolean flag arguments are a sign the function does two things — split it instead. ## 11. Consistency - If the codebase does something one way, **do it the same way**. Don't mix styles. - Consistent naming patterns, consistent structure, consistent error handling. - When joining an existing codebase, **match the existing conventions** even if you'd prefer a different style. - Surprise is the enemy of readability — predictable code is readable code. ## 12. Write Less Code - The best code is **no code at all**. Question whether a feature is truly needed before implementing. - **Don't over-engineer.** Solve the problem at hand, not hypothetical future problems. - Remove dead code. Commented-out code is dead code. - Use standard libraries before writing custom solutions. ## 13. Comments: Explain Why, Not What - Don't comment **what** the code does — the code already says that. Comment **why** it does it. - Comment **flaws and workarounds**: `// TODO:`, `// HACK:`, `// XXX:` with explanation. - Comment **surprising behavior** or non-obvious decisions — things where a reader would ask "why?". - **Don't comment bad code — rewrite it.** If you need a comment to explain what a block does, extract it into a well-named function instead. ## 14. Design Code to Survive Auto-Formatting - Write code that looks good **after** the auto-formatter runs. If a chained expression or repeated pattern would be broken across 4+ lines by the formatter, extract a helper function instead. - **Prefer one-line helper calls** over long inline chains that the formatter will expand vertically. - The formatter is your reader's first impression. Run it *before* committing — if the result looks ugly, that's a signal to refactor, not to disable the formatter. ```python # Bad: black wraps this into a multi-line mess result = ( client.get_session() .query(User) .filter(User.active == True) .options(joinedload(User.orders)) .order_by(User.created_at.desc()) .limit(page_size) .all() ) # Good: extract a helper so the call site stays clean def get_active_users(session, page_size: int) -> list[User]: return ( session.query(User) .filter(User.active == True) .options(joinedload(User.orders)) .order_by(User.created_at.desc()) .limit(page_size) .all() ) users = get_active_users(client.get_session(), page_size=20) ``` ```python # Bad: dict comprehension with inline chain — black expands to 5+ lines config = { k: settings.get(k, defaults.get(k, fallbacks.get(k, None))) for k in required_keys } # Good: extract the lookup def resolve_setting(key, settings, defaults, fallbacks): return settings.get(key, defaults.get(key, fallbacks.get(key))) config = {k: resolve_setting(k, settings, defaults, fallbacks) for k in required_keys} ``` --- # Python-Specific Rules ## 15. Prefer Comprehensions — But Keep Them Simple - Use list/dict/set comprehensions for **simple transforms and filters**. - If a comprehension needs a nested loop AND a conditional, it's too complex — use a regular loop or extract a helper. - Generator expressions for large sequences to avoid materializing the whole list. ```python # Good: simple and readable names = [user.name for user in users if user.is_active] # Bad: too much going on result = [transform(item) for group in data for item in group.items if item.valid and item.type == "A"] # Good: break it up valid_items = get_valid_items(data, item_type="A") result = [transform(item) for item in valid_items] ``` ## 16. Use Unpacking - **Tuple unpacking** over index access: `name, age = get_user()` not `result[0], result[1]`. - **Star unpacking** for head/tail: `first, *rest = items`. - **Dict unpacking** with `**` for merging dicts. - Unpacking makes the structure of the data explicit in the code. ## 17. Use `enumerate`, `zip`, and Itertools - Use `enumerate(items)` — never track indices manually with `i += 1`. - Use `zip(a, b)` to iterate in parallel — never index into parallel lists. - Use `itertools` (`chain`, `groupby`, `islice`) before writing manual iteration logic. ## 18. Use Dataclasses and NamedTuples Over Raw Dicts/Tuples - If a dict always has the same keys, it should be a `dataclass` or `NamedTuple`. - If a function returns more than 2 values, return a `dataclass` or `NamedTuple` — not a raw tuple. - This gives you names, type hints, and readable attribute access for free. ## 19. Use `pathlib` for File Paths - Use `pathlib.Path` instead of `os.path.join` and string manipulation. - `Path` objects are readable, composable (`/` operator), and cross-platform..claude-plugin/marketplace.jsonmarketplaceShow content (451 bytes)
{ "name": "pysheeet", "owner": { "name": "crazyguitar" }, "plugins": [ { "name": "pysheeet", "source": { "source": "github", "repo": "crazyguitar/pysheeet" }, "description": "Comprehensive Python programming reference covering syntax, concurrency, networking, databases, ML/LLM development, and HPC", "version": "1.0.0", "author": { "name": "crazyguitar" } } ] }
README
.. raw:: html
<h1 align="center">
<br>
<a href="https://www.pythonsheets.com"><img src="docs/_static/logo.png" alt="pysheeet" width=200"></a>
</h1>
<p align="center">
<a href="https://github.com/crazyguitar/pysheeet/actions">
<img src="https://github.com/crazyguitar/pysheeet/actions/workflows/pythonpackage.yml/badge.svg" alt="Build Status">
</a>
<a href="https://coveralls.io/github/crazyguitar/pysheeet?branch=master">
<img src="https://coveralls.io/repos/github/crazyguitar/pysheeet/badge.svg?branch=master" alt="Coverage">
</a>
<a href="https://raw.githubusercontent.com/crazyguitar/pysheeet/master/LICENSE">
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License MIT">
</a>
<a href="https://doi.org/10.5281/zenodo.15529042">
<img src="https://zenodo.org/badge/52760178.svg" alt="DOI">
</a>
</p>
Introduction
This project was started to bring together useful Python code snippets that make
coding faster, easier, and more enjoyable. You can explore all the cheat sheets at
Pysheeet <https://www.pythonsheets.com/>_. Contributions are always welcome—feel
free to fork the repo and submit a pull request to help it grow!
Plugin
pysheeet is available as a Claude Code plugin. Once installed, Claude automatically uses the cheat sheets to answer Python questions — just ask naturally and the skill triggers based on context.
Installation
As a Claude Code plugin (recommended):
.. code-block:: bash
# Step 1: Add the marketplace
claude plugin marketplace add crazyguitar/pysheeet
# Step 2: Install the plugin
claude plugin install pysheeet@pysheeet
Local testing (single session only):
.. code-block:: bash
claude --plugin-dir /path/to/pysheeet
Manual installation (requires cloning the repo):
.. code-block:: bash
git clone https://github.com/crazyguitar/pysheeet.git
mkdir -p ~/.claude/skills
cp -r pysheeet/skills/py ~/.claude/skills/py
Python Interview Cheatsheet
Curated Python interview questions indexed by topic — each question links directly to the section of the cheat sheet that answers it. Use it for quick review before an interview, or to drill down on a specific area (GIL, asyncio, decorators, MRO, and more).
Python Interview Cheatsheet <docs/notes/interview/index.rst>_
What's New In Python 3
This part only provides a quick glance at some important features in Python 3.
If you're interested in all of the most important features, please read the
official document, What’s New in Python <https://docs.python.org/3/whatsnew/index.html>_.
New in Python3 <docs/notes/python-new-py3.rst>_
Cheat Sheet
Core Python fundamentals including data types, functions, classes, and commonly used patterns for everyday programming tasks.
From Scratch <docs/notes/basic/python-basic.rst>_Future <docs/notes/basic/python-future.rst>_Typing <docs/notes/basic/python-typing.rst>_Class <docs/notes/basic/python-object.rst>_Function <docs/notes/basic/python-func.rst>_Unicode <docs/notes/basic/python-unicode.rst>_List <docs/notes/basic/python-list.rst>_Set <docs/notes/basic/python-set.rst>_Dictionary <docs/notes/basic/python-dict.rst>_Heap <docs/notes/basic/python-heap.rst>_Generator <docs/notes/basic/python-generator.rst>_Regular expression <docs/notes/basic/python-rexp.rst>_
System
Date/time handling, file I/O, and operating system interfaces.
Datetime <docs/notes/os/python-date.rst>_ - Timestamps, formatting, parsing, timezones, timedeltaFiles and I/O <docs/notes/os/python-io.rst>_ - Reading, writing, pathlib, shutil, tempfileOperating System <docs/notes/os/python-os.rst>_ - Processes, environment, system calls
Concurrency
Threading, multiprocessing, and concurrent.futures for parallel execution. Covers synchronization primitives, process pools, and bypassing the GIL.
Threading <docs/notes/concurrency/python-threading.rst>_ - Threads, locks, semaphores, events, conditionsMultiprocessing <docs/notes/concurrency/python-multiprocessing.rst>_ - Processes, pools, shared memory, IPCconcurrent.futures <docs/notes/concurrency/python-futures.rst>_ - Executors, futures, callbacks
Asyncio
Asynchronous programming with Python's asyncio module. Covers coroutines,
event loops, tasks, networking, and advanced patterns.
A Hitchhiker's Guide to Asynchronous Programming <docs/notes/asyncio/python-asyncio-guide.rst>_ - Design philosophy and evolutionAsyncio Basics <docs/notes/asyncio/python-asyncio-basic.rst>_ - Coroutines, tasks, gather, timeoutsAsyncio Networking <docs/notes/asyncio/python-asyncio-server.rst>_ - TCP/UDP servers, HTTP, SSL/TLSAsyncio Advanced <docs/notes/asyncio/python-asyncio-advanced.rst>_ - Synchronization, queues, subprocesses
C/C++ Extensions
Native extensions for performance-critical code. Covers modern pybind11 (used by PyTorch, TensorFlow), ctypes, cffi, Cython, and the traditional Python C API. Also includes a guide for Python developers learning modern C++ syntax.
ctypes <docs/notes/extension/python-ctypes.rst>_ - Load shared libraries without compilationPython C API <docs/notes/extension/python-capi.rst>_ - Traditional C extension referenceModern C/C++ Extensions <docs/notes/extension/python-cext-modern.rst>_ - pybind11, CythonLearn C++ from Python <docs/notes/extension/cpp-from-python.rst>_ - Modern C++ for Python developers
Security
Modern cryptographic practices and common security vulnerabilities. Covers encryption, TLS/SSL, and why legacy patterns are dangerous.
Modern Cryptography <docs/notes/security/python-crypto.rst>_ - AES-GCM, RSA-OAEP, Ed25519, Argon2TLS/SSL and Certificates <docs/notes/security/python-tls.rst>_ - HTTPS servers, certificate generationCommon Vulnerabilities <docs/notes/security/python-vulnerability.rst>_ - Padding oracle, injection, timing attacks
Network
Low-level network programming with Python sockets. Covers TCP/UDP communication, server implementations, asynchronous I/O, SSL/TLS encryption, and packet analysis.
Socket Basics <docs/notes/network/python-socket.rst>_Socket Servers <docs/notes/network/python-socket-server.rst>_Async Socket I/O <docs/notes/network/python-socket-async.rst>_SSL/TLS Sockets <docs/notes/network/python-socket-ssl.rst>_Packet Sniffing <docs/notes/network/python-socket-sniffer.rst>_SSH and Tunnels <docs/notes/network/python-ssh.rst>_
Database
Database access with SQLAlchemy, Python's most popular ORM. Covers connection management, raw SQL, object-relational mapping, and common query patterns.
SQLAlchemy Basics <docs/notes/database/python-sqlalchemy.rst>_SQLAlchemy ORM <docs/notes/database/python-sqlalchemy-orm.rst>_SQLAlchemy Query Recipes <docs/notes/database/python-sqlalchemy-query.rst>_
LLM
Large Language Models (LLM) training, inference, and optimization. Covers PyTorch for model development, distributed training across GPUs, and vLLM/SGLang for high-performance LLM inference and serving.
PyTorch <docs/notes/llm/pytorch.rst>_ - Tensors, autograd, neural networks, training loopsMegatron <docs/notes/llm/megatron.rst>_ - NVIDIA Megatron training/fine-tuning framework with enroot/pyxisLLM Serving <docs/notes/llm/llm-serving.rst>_ - vLLM and SGLang for production inference with TP/PP/DP/EPLLM Benchmark <docs/notes/llm/llm-bench.rst>_ - Benchmark suite for measuring serving performance
HPC
High-Performance Computing tools for cluster management and job scheduling. Covers Slurm workload manager and Ray for distributed computing on GPU clusters.
Slurm <docs/notes/hpc/slurm.rst>_Ray Cluster <docs/notes/hpc/ray.rst>_
Blog
Supplementary topics covering Python internals, debugging techniques, and language features that don't fit elsewhere.
NVSHMEM Multi-NIC Support with AWS EFA <docs/notes/appendix/nvshmem-multi-nic.rst>_Is Disaggregated Prefill/Decode a Silver Bullet for LLM Serving? <docs/notes/appendix/disaggregated-prefill-decode.rst>_Monitoring EFA with NCCL GIN and Nsys <docs/notes/appendix/megatron-efa-monitoring.rst>_GPU-Initiated Networking for NCCL on AWS <docs/notes/appendix/nccl-gin.rst>_PEP 572 and the walrus operator <docs/notes/appendix/python-walrus.rst>_Python Interpreter in GNU Debugger <docs/notes/appendix/python-gdb.rst>_
PDF Version
pdf_
.. _pdf: https://media.readthedocs.org/pdf/pysheeet/latest/pysheeet.pdf
How to run the server
.. code-block:: bash
$ virtualenv venv
$ . venv/bin/activate
$ pip install -r requirements.txt
$ make
$ python app.py
# URL: localhost:5000