{"data":{"slug":"discovered-5e385238a1d93858f8b5787c0d7a326901c1f9ee6edc2aba","title":"Python Programming","summary":"Write Python code that is readable, type-checked, and follows best practices for structure, data modeling, error handling, and concurrency. Deliverables include type-annotated functions, dataclasses, Pydantic models, and tests using pytest.","url":"https:\/\/skillshunter.net\/skills\/discovered-5e385238a1d93858f8b5787c0d7a326901c1f9ee6edc2aba","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-5e385238a1d93858f8b5787c0d7a326901c1f9ee6edc2aba","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-5e385238a1d93858f8b5787c0d7a326901c1f9ee6edc2aba.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-5e385238a1d93858f8b5787c0d7a326901c1f9ee6edc2aba\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure the project uses Python 3.11 or later. Use `pyproject.toml` for project configuration and `uv` for environment management. Prefer `ruff` for formatting and linting over separate tools like black or flake8. Use `@dataclass(frozen=True, slots=True)` for internal records and Pydantic models for parsing and validating external data.","instructions":"---\nname: python-programming\ndescription: Use when writing, reviewing, refactoring or debugging Python code - new modules, scripts or CLIs, type hints, dataclasses and data modelling, error handling, asyncio, pytest tests, project setup with pyproject.toml, tooling (uv, ruff, mypy, pyright), or performance work. Triggers - \"write a Python function or class\", \"add type hints\", \"make this more Pythonic\", \"refactor this module\", \"why is this slow\", \"set up a Python project\", \"write tests for this\", import or packaging errors, mutable default arguments, async bugs.\n---\n\n# Python Programming\n\nWrite Python that a reader can follow top to bottom and a type checker can\nverify. Most defects in Python code are things a checker or a test would have\ncaught, so the habit that pays is making them able to catch it.\n\n**Match the project first.** Before writing, read `pyproject.toml` (or\n`setup.cfg`, `requirements*.txt`) for the Python version, formatter, linter and\ntest runner, and look at two existing modules for naming and layout. The\nproject's conventions win over the defaults below.\n\n## Defaults for new code\n\nTarget Python 3.11 or later unless the project says otherwise.\n\n| Decision | Default | Instead of |\n|---|---|---|\n| Project and dependencies | `pyproject.toml`, `uv` for environments and locking | `setup.py`, bare `requirements.txt` |\n| Layout | `src\/<package>\/`, `tests\/` beside it | package at the repository root |\n| Format and lint | `ruff format` and `ruff check` | separate black, isort, flake8 |\n| Types | built-in generics (`list[str]`), `X \\| None`, `collections.abc` for parameters | `typing.List`, `Optional`, `Union` |\n| Records | `@dataclass(frozen=True, slots=True)` | dicts with string keys, hand-written `__init__` |\n| Untrusted input | Pydantic model at the boundary | manual `isinstance` chains |\n| Fixed choices | `enum.StrEnum` | string constants |\n| Paths | `pathlib.Path` | `os.path` string joins |\n| Time | `datetime.now(UTC)`, always timezone-aware | `datetime.utcnow()` (deprecated, returns naive) |\n| Concurrency (I\/O) | `asyncio.TaskGroup`, `asyncio.timeout` | bare `gather`, manual task bookkeeping |\n| Concurrency (CPU) | `ProcessPoolExecutor`, or vectorize | threads |\n| Config | `tomllib`, environment variables, typed settings object | globals, `eval` |\n| Logging | `logging.getLogger(__name__)`, `%s` arguments | `print`, f-strings in log calls |\n| Tests | `pytest`, plain `assert`, `tmp_path`, `monkeypatch` | `unittest.TestCase` boilerplate |\n\n## Types\n\n- Annotate every function signature. Annotate locals only where inference fails.\n- Accept the widest type that works (`Iterable[str]`, `Mapping[str, int]`), return\n  the narrowest (`list[str]`). Callers stay flexible and get precise results.\n- Use `Protocol` for \"anything with this method\" instead of a base class the\n  caller must inherit from.\n- `Any` switches the checker off for everything it touches. Prefer `object` for\n  \"anything\", and narrow with `isinstance` or `match`.\n- Make illegal states unrepresentable: an enum or a union of dataclasses beats a\n  status string plus optional fields that are only valid together.\n\n## Choosing a data container\n\n| Need | Use |\n|---|---|\n| Internal record with behaviour | `@dataclass(frozen=True, slots=True)` |\n| Parsing and validating external data (JSON, env, user input) | Pydantic model |\n| Describing the shape of a dict you do not control | `TypedDict` |\n| Small immutable tuple with names | `NamedTuple` |\n| Closed set of values | `StrEnum` \/ `Enum` |\n\n## Errors\n\n- Raise specific exceptions with a message that names the offending value. Define\n  one base exception per package so callers can catch the package's errors.\n- Catch only what you can handle, at the level that can handle it. `except\n  Exception: pass` hides the bug and the next person's afternoon.\n- Chain with `raise NewError(...) from err` so the original traceback survives.\n- Validate at the boundary (API handler, CLI, file loader), then trust types inside.\n- Use context managers for anything that must be released.\n\n## Async\n\n- Async helps with many concurrent waits (network, disk). It does nothing for CPU\n  work, and one blocking call (`time.sleep`, `requests.get`, a heavy loop) stalls\n  every task. Push blocking work to `asyncio.to_thread`.\n- Start concurrent work in a `TaskGroup`: if one task fails the rest are\n  cancelled and the error surfaces. A task created and not awaited can vanish\n  with its exception.\n- Put a timeout on every external call, and bound concurrency with a `Semaphore`.\n\n## Tests\n\n- Test behaviour through the public interface. Tests that mirror the\n  implementation break on every refactor and catch nothing.\n- One reason to fail per test; name it after the behaviour\n  (`test_rejects_negative_quantity`).\n- `pytest.mark.parametrize` for input tables, fixtures for setup, `tmp_path` for\n  files, `monkeypatch` for environment and attributes.\n- Mock at the boundary you do not own (network, clock, filesystem), and patch\n  where the name is looked up, not where it is defined.\n- A bug fix starts with a test that fails for the reported reason.\n\n## Performance\n\nMeasure before changing anything: `python -m cProfile -s cumtime script.py`, or\n`py-spy` on a running process. Then, in order of payoff:\n\n1. A better algorithm or data structure (`set` and `dict` lookups, not list scans).\n2. Fewer round trips: batch queries and I\/O.\n3. Vectorize numeric work with NumPy, pandas or Polars.\n4. Cache pure functions (`functools.cache`).\n5. Processes for CPU-bound work; native code last.\n\nGenerators keep memory flat for large streams; lists are faster for small ones.\n\n## Gotchas\n\n| Trap | What happens | Fix |\n|---|---|---|\n| `def f(x, items=[])` | the default list is shared across calls | `items: list \\| None = None`, create inside |\n| Closures in a loop (`lambda: i`) | all see the final `i` | bind it: `lambda i=i: i` |\n| `is` for value comparison | works for small ints and some strings by accident | `==` for values, `is` only for `None` and sentinels |\n| Modifying a list while iterating it | skipped elements | iterate over a copy or build a new list |\n| Naive datetimes | silent errors across time zones and DST | timezone-aware everywhere, convert at the edge |\n| Floats for money | `0.1 + 0.2 != 0.3` | `Decimal` or integer minor units |\n| `except:` or broad `except Exception` | swallows `KeyboardInterrupt` or real bugs | catch the specific error |\n| Circular imports | `ImportError` or partially initialised modules | move shared types to a third module; import inside the function as a last resort |\n| Opening files without `with` | leaked handles | context manager |\n\n## Before calling it done\n\n```bash\nruff format . && ruff check . --fix\nmypy src            # or: pyright\npytest -q\n```\n\nRun them and read the output. If the project has no configuration for one of\nthese, say so instead of inventing a passing result.\n\n## References\n\n| File | When |\n|---|---|\n| `references\/patterns.md` | worked examples: dataclasses, Protocol, StrEnum with match, error chaining, context managers, TaskGroup with timeout and bounded concurrency, pytest patterns |\n| `references\/project-setup.md` | pyproject.toml template, uv commands, ruff and mypy configuration, pre-commit, CI |\n","use_cases":["Add type hints to existing Python functions","Refactor a Python module to use dataclasses and type annotations","Set up a new Python project with pyproject.toml and uv","Write tests for Python code using pytest","Improve concurrency handling with asyncio and TaskGroup"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/Ricko12vPL\/claude-code-skills\/blob\/4bc1ba2d54dcd4ac48cef1689efd4ccb48de9c75\/skills\/python-programming\/SKILL.md","source_commit":"4bc1ba2d54dcd4ac48cef1689efd4ccb48de9c75","license":null,"version":null,"listing_approved_at":"2026-11-29","created_at":"2026-11-28T18:52:28.000000Z","updated_at":"2026-11-29T10:53:39.000000Z","seo_title":"Python Programming Best Practices","seo_description":"Learn how to write clean, type-annotated Python code with best practices for data modeling, error handling, and testing.","seo_keywords":["Python programming","type hints","dataclasses","Pydantic","pytest","asyncio","Python best practices"]}}