pysheeet
Python Cheat Sheet
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/crazyguitar/pysheeet with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/crazyguitar/pysheeet'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/crazyguitar--pysheeet)HTML
<a href="/listings/crazyguitar--pysheeet"><img src="/api/listings/crazyguitar--pysheeet/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
**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
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 20 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "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.rst · README · 242 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- .. 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, timedelta
- - `Files and I/O <docs/notes/os/python-io.rst>`_ - Reading, writing, pathlib, shutil, tempfile
- - `Operating 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, conditions
- - `Multiprocessing <docs/notes/concurrency/python-multiprocessing.rst>`_ - Processes, pools, shared memory, IPC
- - `concurrent.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 evolution
- - `Asyncio Basics <docs/notes/asyncio/python-asyncio-basic.rst>`_ - Coroutines, tasks, gather, timeouts
- - `Asyncio Networking <docs/notes/asyncio/python-asyncio-server.rst>`_ - TCP/UDP servers, HTTP, SSL/TLS
- - `Asyncio 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 compilation
- - `Python C API <docs/notes/extension/python-capi.rst>`_ - Traditional C extension reference
- - `Modern C/C++ Extensions <docs/notes/extension/python-cext-modern.rst>`_ - pybind11, Cython
- - `Learn 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, Argon2
- - `TLS/SSL and Certificates <docs/notes/security/python-tls.rst>`_ - HTTPS servers, certificate generation
- - `Common 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 loops
- - `Megatron <docs/notes/llm/megatron.rst>`_ - NVIDIA Megatron training/fine-tuning framework with enroot/pyxis
- - `LLM Serving <docs/notes/llm/llm-serving.rst>`_ - vLLM and SGLang for production inference with TP/PP/DP/EP
- - `LLM 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.
- - `NCCL Multi-Rail Broadcast with More GPU Ranks <docs/notes/appendix/nccl-ring.rst>`_
- - `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
src/security/vulnerability_.py · Bundled script · 256 lines · 4 findings marked
- """Tests demonstrating security vulnerabilities and secure alternatives."""
- import pytest
- import hmac
- import secrets
- import os
- class TestTimingAttack:
- """Demonstrate timing attack vulnerability in string comparison."""
- def test_insecure_comparison(self):
- """Insecure comparison - vulnerable to timing attack."""
- secret = b"correct_secret_token"
- def insecure_compare(a, b):
- """INSECURE: Returns early on mismatch."""
- if len(a) != len(b):
- return False
- for x, y in zip(a, b):
- if x != y:
- return False
- return True
- # These comparisons take different amounts of time
- assert insecure_compare(secret, secret) == True
- assert insecure_compare(secret, b"wrong_secret_token!") == False
- assert insecure_compare(secret, b"c") == False
- def test_secure_comparison(self):
- """Secure comparison using hmac.compare_digest."""
- secret = b"correct_secret_token"
- # Constant-time comparison - safe from timing attacks
- assert hmac.compare_digest(secret, secret) == True
- assert hmac.compare_digest(secret, b"wrong_secret_token!") == False
- class TestWeakRandom:
- """Demonstrate weak vs strong random number generation."""
- def test_weak_random(self):
- """INSECURE: random module is predictable."""
- import random
- # Mersenne Twister can be predicted after observing outputs
- random.seed(12345)
- values = [random.randint(0, 100) for _ in range(10)]
- # Same seed produces same sequence - predictable!
- random.seed(12345)
- values2 = [random.randint(0, 100) for _ in range(10)]
- assert values == values2
- def test_secure_random(self):
- """SECURE: secrets module uses OS entropy."""
- # Cryptographically secure random
- token1 = secrets.token_hex(16)
- token2 = secrets.token_hex(16)
- # Each call produces unique, unpredictable value
- assert token1 != token2
- assert len(token1) == 32
- class TestSQLInjection:
- """Demonstrate SQL injection vulnerability."""
- def test_vulnerable_query_building(self):
- """INSECURE: String formatting in SQL."""
- def build_query_insecure(username):
- # VULNERABLE: User input directly in query
- return f"SELECT * FROM users WHERE username = '{username}'"
- # Normal input
- query = build_query_insecure("alice")
- assert query == "SELECT * FROM users WHERE username = 'alice'"
- # Malicious input - SQL injection!
- malicious = "admin' OR '1'='1"
- query = build_query_insecure(malicious)
- # This would return ALL users!
- assert "OR '1'='1'" in query
- def test_parameterized_query(self):
- """SECURE: Parameterized queries prevent injection."""
- def build_query_secure(username):
- # Parameters are escaped by the database driver
- return ("SELECT * FROM users WHERE username = ?", (username,))
- query, params = build_query_secure("admin' OR '1'='1")
- # The malicious input is treated as a literal string
- assert params == ("admin' OR '1'='1",)
- class TestCommandInjection:
- """Demonstrate command injection vulnerability."""
- def test_vulnerable_shell_command(self):
- """INSECURE: User input in shell command."""
- def build_command_insecure(filename):
- # VULNERABLE: Shell injection possible
- return f"cat {filename}"
- # Malicious input
- malicious = "file.txt; rm -rf /"
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 109 on GitHub
- cmd = build_command_insecure(malicious)
- # Would execute: cat file.txt; rm -rf /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 111 on GitHub
- assert "; rm -rf /" in cmd
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 112 on GitHub
- def test_secure_command(self):
- """SECURE: Use argument list, not shell string."""
- import shlex
- def build_command_secure(filename):
- # Validate and use list of arguments
- if not filename.replace(".", "").replace("_", "").isalnum():
- raise ValueError("Invalid filename")
- return ["cat", filename]
- # Malicious input is rejected
- with pytest.raises(ValueError):
- build_command_secure("file.txt; rm -rf /")
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 126 on GitHub
- # Valid input works
- cmd = build_command_secure("file.txt")
- assert cmd == ["cat", "file.txt"]
- class TestPickleVulnerability:
- """Demonstrate pickle deserialization vulnerability."""
- def test_pickle_code_execution(self):
- """INSECURE: Pickle can execute arbitrary code."""
- import pickle
- class MaliciousPayload:
- def __reduce__(self):
- # This would execute when unpickled!
- # return (os.system, ("echo HACKED",))
- # For safety, we just return a harmless function
- return (str, ("PAYLOAD_EXECUTED",))
- # Attacker creates malicious pickle
- malicious_data = pickle.dumps(MaliciousPayload())
- # Victim unpickles - code executes!
- result = pickle.loads(malicious_data)
- assert result == "PAYLOAD_EXECUTED"
- def test_safe_json(self):
- """SECURE: JSON cannot execute code."""
- import json
- data = {"user": "alice", "role": "admin"}
- serialized = json.dumps(data)
- deserialized = json.loads(serialized)
- assert deserialized == data
- # JSON only supports basic types - no code execution
- class TestHardcodedSecrets:
- """Demonstrate hardcoded secrets vulnerability."""
- def test_environment_variables(self):
- """SECURE: Use environment variables for secrets."""
- # Set a test secret
- os.environ["TEST_API_KEY"] = "secret_key_123"
- # Read from environment
- api_key = os.environ.get("TEST_API_KEY")
- assert api_key == "secret_key_123"
- # Clean up
- del os.environ["TEST_API_KEY"]
- # Missing secret should be handled
- missing = os.environ.get("NONEXISTENT_KEY")
- assert missing is None
- class TestAESModes:
- """Demonstrate AES mode vulnerabilities."""
- def test_ecb_mode_pattern_leak(self):
- """INSECURE: ECB mode leaks patterns in plaintext."""
- # ECB encrypts identical blocks to identical ciphertext
- # This reveals patterns in the data
- # Simulated ECB behavior (without actual crypto)
- def fake_ecb_encrypt(blocks):
- # Same input block -> same output (pattern leak!)
- block_map = {}
- result = []
- for i, block in enumerate(blocks):
- if block not in block_map:
- block_map[block] = f"cipher_{i}"
- result.append(block_map[block])
- return result
- # Repeated plaintext blocks
- blocks = ["AAAA", "BBBB", "AAAA", "CCCC", "AAAA"]
- encrypted = fake_ecb_encrypt(blocks)
- # Pattern is visible! Same plaintext -> same ciphertext
- assert encrypted[0] == encrypted[2] == encrypted[4]
- def test_cbc_needs_authentication(self):
- """AES-CBC without authentication is vulnerable."""
- # CBC provides confidentiality but not integrity
- # Attacker can modify ciphertext without detection
- # This enables padding oracle attacks
- # AES-GCM provides both confidentiality AND integrity
- # Tampering is detected and rejected
- pass
- class TestPasswordStorage:
- """Demonstrate password storage vulnerabilities."""
- def test_weak_hash(self):
- """INSECURE: MD5/SHA1 for passwords."""
- import hashlib
- password = "password123"
- # INSECURE: Fast hashes are easily brute-forced
- md5_hash = hashlib.md5(password.encode()).hexdigest()
- sha1_hash = hashlib.sha1(password.encode()).hexdigest()
- # These can be cracked in seconds with rainbow tables
- assert len(md5_hash) == 32
- assert len(sha1_hash) == 40
- def test_secure_password_hash(self):
- """SECURE: Use slow, salted password hashing."""
- # In production, use argon2-cffi or bcrypt
- # This is a simplified demonstration
- import hashlib
- password = "password123"
- salt = secrets.token_bytes(16)
- # PBKDF2 with high iteration count (still not ideal, use Argon2)
- hash_value = hashlib.pbkdf2_hmac(
- "sha256", password.encode(), salt, iterations=100000
- )
- assert len(hash_value) == 32
- assert len(salt) == 16
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.