Python Pro Modern Python 3.11+ specialist focused on type-safe, async-first, production-ready code. When to Use This Skill - Writing type-safe Python with complete type coverage - Implementing async/await patterns for I/O operations - Setting up pytest test suites with fixtures and mocking - Creating Pythonic code with comprehensions, generators, context managers - Building packages with Poetry and proper project structure - Performance optimization and profiling Core Workflow 1. Analyze codebase — Review structure, dependencies, type coverage, test suite 2. Design interfaces — Define protoco…

\n\n[tool.ruff]\nline-length = 100\ntarget-version = \"py311\"\nselect = [\n \"E\", # pycodestyle errors\n \"W\", # pycodestyle warnings\n \"F\", # pyflakes\n \"I\", # isort\n \"B\", # flake8-bugbear\n \"C4\", # flake8-comprehensions\n \"UP\", # pyupgrade\n]\nignore = []\n\n[tool.ruff.per-file-ignores]\n\"__init__.py\" = [\"F401\"] # Ignore unused imports in __init__.py\n\n[tool.mypy]\npython_version = \"3.11\"\nstrict = true\nwarn_return_any = true\nwarn_unused_configs = true\ndisallow_untyped_defs = true\n\n[[tool.mypy.overrides]]\nmodule = \"third_party.*\"\nignore_missing_imports = true\n\n[tool.pytest.ini_options]\nminversion = \"7.0\"\naddopts = [\n \"-ra\",\n \"--strict-markers\",\n \"--strict-config\",\n \"--cov=myproject\",\n \"--cov-report=term-missing\",\n \"--cov-report=html\",\n]\ntestpaths = [\"tests\"]\npythonpath = [\"src\"]\n\n[tool.coverage.run]\nsource = [\"src\"]\nbranch = true\n\n[tool.coverage.report]\nexclude_lines = [\n \"pragma: no cover\",\n \"def __repr__\",\n \"raise AssertionError\",\n \"raise NotImplementedError\",\n \"if __name__ == .__main__.:\",\n \"if TYPE_CHECKING:\",\n]\n```\n\n## Poetry Project Management\n\n```toml\n# pyproject.toml for Poetry\n[tool.poetry]\nname = \"myproject\"\nversion = \"0.1.0\"\ndescription = \"A Python project\"\nauthors = [\"Your Name \[email protected]>\"]\nreadme = \"README.md\"\nlicense = \"MIT\"\npackages = [{include = \"myproject\", from = \"src\"}]\n\n[tool.poetry.dependencies]\npython = \"^3.11\"\nrequests = \"^2.31.0\"\npydantic = \"^2.5.0\"\n\n[tool.poetry.group.dev.dependencies]\npytest = \"^7.4.0\"\npytest-cov = \"^4.1.0\"\nmypy = \"^1.7.0\"\nblack = \"^23.11.0\"\nruff = \"^0.1.6\"\n\n[tool.poetry.scripts]\nmyproject = \"myproject.cli:main\"\n\n[build-system]\nrequires = [\"poetry-core\"]\nbuild-backend = \"poetry.core.masonry.api\"\n```\n\n```bash\n# Poetry commands\npoetry init # Initialize new project\npoetry add requests # Add dependency\npoetry add --group dev pytest # Add dev dependency\npoetry install # Install dependencies\npoetry update # Update dependencies\npoetry shell # Activate virtual environment\npoetry run pytest # Run command in venv\npoetry build # Build package\npoetry publish # Publish to PyPI\npoetry export -f requirements.txt --output requirements.txt\n```\n\n## Virtual Environments\n\n```bash\n# Using venv (built-in)\npython -m venv .venv\nsource .venv/bin/activate # Linux/Mac\n.venv\\Scripts\\activate # Windows\n\n# Install in editable mode\npip install -e .\npip install -e \".[dev]\" # With optional dependencies\n\n# Using virtualenv\npip install virtualenv\nvirtualenv venv\nsource venv/bin/activate\n\n# Using pyenv for Python version management\npyenv install 3.11.6\npyenv local 3.11.6 # Set for current directory\necho \"3.11.6\" > .python-version\n```\n\n## Package __init__.py\n\n```python\n# src/myproject/__init__.py\n\"\"\"MyProject - A Python package.\"\"\"\n\nfrom myproject.core import main_function, CoreClass\nfrom myproject.utils import helper_function\n\n__version__ = \"0.1.0\"\n__all__ = [\"main_function\", \"CoreClass\", \"helper_function\"]\n\n# Package-level configuration\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n```\n\n## Type Stub Files (py.typed)\n\n```python\n# src/myproject/py.typed\n# Empty file indicates package includes type hints\n\n# src/myproject/__init__.pyi (optional stub file)\nfrom typing import Any\n\n__version__: str\n\ndef main_function(arg: str) -> dict[str, Any]: ...\n\nclass CoreClass:\n def __init__(self, name: str) -> None: ...\n def process(self) -> str: ...\n```\n\n## CLI Entry Points\n\n```python\n# src/myproject/cli.py\nimport sys\nfrom typing import NoReturn\n\ndef main() -> NoReturn:\n \"\"\"Main CLI entry point.\"\"\"\n print(\"MyProject CLI\")\n sys.exit(0)\n\nif __name__ == \"__main__\":\n main()\n```\n\n## Requirements Files\n\n```bash\n# requirements.txt - Production dependencies\nrequests>=2.31.0,\u003c3.0.0\npydantic>=2.5.0,\u003c3.0.0\n\n# requirements-dev.txt - Development dependencies\n-r requirements.txt\npytest>=7.4.0\npytest-cov>=4.1.0\nmypy>=1.7.0\nblack>=23.11.0\nruff>=0.1.6\n\n# Generate from Poetry\npoetry export -f requirements.txt --output requirements.txt --without-hashes\npoetry export -f requirements.txt --with dev --output requirements-dev.txt\n```\n\n## Building and Distribution\n\n```bash\n# Build package\npython -m build\n\n# Check package\ntwine check dist/*\n\n# Upload to PyPI\ntwine upload dist/*\n\n# Upload to Test PyPI\ntwine upload --repository testpypi dist/*\n\n# Install from Test PyPI\npip install --index-url https://test.pypi.org/simple/ myproject\n```\n\n## Setuptools Configuration (Legacy)\n\n```python\n# setup.py (if not using pyproject.toml)\nfrom setuptools import setup, find_packages\n\nsetup(\n name=\"myproject\",\n version=\"0.1.0\",\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n python_requires=\">=3.11\",\n install_requires=[\n \"requests>=2.31.0\",\n \"pydantic>=2.5.0\",\n ],\n extras_require={\n \"dev\": [\n \"pytest>=7.4.0\",\n \"mypy>=1.7.0\",\n ],\n },\n entry_points={\n \"console_scripts\": [\n \"myproject=myproject.cli:main\",\n ],\n },\n)\n```\n\n## Manifest for Package Data\n\n```\n# MANIFEST.in\ninclude README.md\ninclude LICENSE\ninclude pyproject.toml\nrecursive-include src/myproject *.py\nrecursive-include src/myproject py.typed\nrecursive-include tests *.py\nprune docs/_build\n```\n\n## Version Management\n\n```python\n# src/myproject/__version__.py\n__version__ = \"0.1.0\"\n\n# src/myproject/__init__.py\nfrom myproject.__version__ import __version__\n\n# Read version in pyproject.toml\nimport tomli\nfrom pathlib import Path\n\ndef get_version() -> str:\n pyproject = Path(__file__).parent.parent / \"pyproject.toml\"\n with open(pyproject, \"rb\") as f:\n data = tomli.load(f)\n return data[\"project\"][\"version\"]\n```\n\n## Dependency Management Best Practices\n\n```python\n# Pin dependencies for applications\nrequests==2.31.0\npydantic==2.5.2\n\n# Use ranges for libraries\nrequests>=2.31.0,\u003c3.0.0\npydantic>=2.5.0,\u003c3.0.0\n\n# Lock files\n# Poetry: poetry.lock\n# pip: requirements.txt with exact versions\npip freeze > requirements-lock.txt\n\n# Update dependencies\npoetry update\npip install --upgrade -r requirements.txt\n```\n\n## CI/CD Integration\n\n```yaml\n# .github/workflows/test.yml\nname: Tests\n\non: [push, pull_request]\n\njobs:\n test:\n runs-on: ubuntu-latest\n strategy:\n matrix:\n python-version: [\"3.11\", \"3.12\"]\n\n steps:\n - uses: actions/checkout@v4\n - name: Set up Python\n uses: actions/setup-python@v4\n with:\n python-version: ${{ matrix.python-version }}\n\n - name: Install dependencies\n run: |\n python -m pip install --upgrade pip\n pip install -e \".[dev]\"\n\n - name: Run tests\n run: |\n pytest --cov --cov-report=xml\n\n - name: Type check\n run: mypy src\n\n - name: Lint\n run: |\n black --check src tests\n ruff check src tests\n\n - name: Upload coverage\n uses: codecov/codecov-action@v3\n```\n\n## Pre-commit Hooks\n\n```yaml\n# .pre-commit-config.yaml\nrepos:\n - repo: https://github.com/psf/black\n rev: 23.11.0\n hooks:\n - id: black\n\n - repo: https://github.com/astral-sh/ruff-pre-commit\n rev: v0.1.6\n hooks:\n - id: ruff\n args: [--fix, --exit-non-zero-on-fix]\n\n - repo: https://github.com/pre-commit/mirrors-mypy\n rev: v1.7.1\n hooks:\n - id: mypy\n additional_dependencies: [types-requests]\n```\n\n```bash\n# Install pre-commit\npip install pre-commit\npre-commit install\n\n# Run manually\npre-commit run --all-files\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":9652,"content_sha256":"483d0a257907d2e17ce1cf2e3e7b8b2af88f9eb17fa3a9c4bcc04aa60e930ae3"},{"filename":"references/standard-library.md","content":"# Standard Library Mastery\n\n## Pathlib for File Operations\n\n```python\nfrom pathlib import Path\n\n# Path creation and manipulation\nproject_root = Path(__file__).parent.parent\nconfig_file = project_root / \"config\" / \"settings.toml\"\ndata_dir = Path.home() / \"data\"\n\n# File operations\ndef read_config(config_path: Path) -> dict[str, str]:\n if not config_path.exists():\n raise FileNotFoundError(f\"Config not found: {config_path}\")\n\n # Read text\n content = config_path.read_text(encoding=\"utf-8\")\n\n # Read bytes\n binary = config_path.read_bytes()\n\n return parse_config(content)\n\n# Path traversal\ndef find_python_files(directory: Path) -> list[Path]:\n # Recursive glob\n return list(directory.rglob(\"*.py\"))\n\ndef get_file_info(path: Path) -> dict[str, Any]:\n stat = path.stat()\n return {\n \"size\": stat.st_size,\n \"modified\": stat.st_mtime,\n \"is_file\": path.is_file(),\n \"is_dir\": path.is_dir(),\n \"suffix\": path.suffix,\n \"stem\": path.stem,\n }\n\n# Creating directories\ndef ensure_dir(path: Path) -> None:\n path.mkdir(parents=True, exist_ok=True)\n\n# Temporary files\nfrom tempfile import TemporaryDirectory\nfrom pathlib import Path\n\ndef process_with_temp() -> None:\n with TemporaryDirectory() as tmpdir:\n temp_path = Path(tmpdir) / \"output.txt\"\n temp_path.write_text(\"data\")\n```\n\n## Dataclasses for Data Structures\n\n```python\nfrom dataclasses import dataclass, field, asdict, replace\nfrom typing import ClassVar\n\n# Basic dataclass\n@dataclass\nclass User:\n id: int\n name: str\n email: str\n active: bool = True\n\n# Post-init processing\n@dataclass\nclass Product:\n name: str\n price: float\n discount: float = 0.0\n\n def __post_init__(self) -> None:\n if self.discount > 1.0:\n raise ValueError(\"Discount must be \u003c= 1.0\")\n\n @property\n def final_price(self) -> float:\n return self.price * (1 - self.discount)\n\n# Field with factory\n@dataclass\nclass ShoppingCart:\n user_id: int\n items: list[str] = field(default_factory=list)\n metadata: dict[str, Any] = field(default_factory=dict)\n\n# Frozen dataclass (immutable)\n@dataclass(frozen=True)\nclass Point:\n x: float\n y: float\n\n def distance(self, other: \"Point\") -> float:\n return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5\n\n# Class variables\n@dataclass\nclass Config:\n API_VERSION: ClassVar[str] = \"v1\"\n BASE_URL: ClassVar[str] = \"https://api.example.com\"\n\n timeout: int = 30\n retries: int = 3\n\n# Ordered dataclass for comparison\n@dataclass(order=True)\nclass Priority:\n level: int\n name: str = field(compare=False)\n\n# Convert to/from dict\nuser = User(1, \"Alice\", \"[email protected]\")\nuser_dict = asdict(user)\nupdated = replace(user, name=\"Alice Smith\")\n```\n\n## Functools for Function Tools\n\n```python\nfrom functools import (\n cache, lru_cache, cached_property,\n partial, wraps, reduce, singledispatch\n)\n\n# Caching\n@cache # Unlimited cache (Python 3.9+)\ndef fibonacci(n: int) -> int:\n if n \u003c 2:\n return n\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n@lru_cache(maxsize=128) # LRU cache with size limit\ndef fetch_user(user_id: int) -> dict[str, Any]:\n # Expensive database call\n return {\"id\": user_id, \"name\": \"User\"}\n\n# Cached property\nclass DataProcessor:\n def __init__(self, data: list[int]) -> None:\n self._data = data\n\n @cached_property\n def mean(self) -> float:\n \"\"\"Computed once, then cached.\"\"\"\n return sum(self._data) / len(self._data)\n\n# Partial application\nfrom operator import mul\n\ndouble = partial(mul, 2)\ntriple = partial(mul, 3)\nprint(double(5)) # 10\n\n# Decorator preservation\ndef timing_decorator(func: Callable[P, R]) -> Callable[P, R]:\n @wraps(func)\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n start = time.time()\n result = func(*args, **kwargs)\n print(f\"{func.__name__} took {time.time() - start:.2f}s\")\n return result\n return wrapper\n\n# Reduce for aggregation\nfrom operator import add\n\ntotal = reduce(add, [1, 2, 3, 4, 5]) # 15\nproduct = reduce(mul, [1, 2, 3, 4], 1) # 24\n\n# Single dispatch for polymorphism\n@singledispatch\ndef process(arg: Any) -> str:\n return f\"Unknown type: {type(arg)}\"\n\[email protected]\ndef _(arg: int) -> str:\n return f\"Integer: {arg * 2}\"\n\[email protected]\ndef _(arg: str) -> str:\n return f\"String: {arg.upper()}\"\n\[email protected](list)\ndef _(arg: list[Any]) -> str:\n return f\"List with {len(arg)} items\"\n```\n\n## Itertools for Iteration\n\n```python\nfrom itertools import (\n chain, islice, cycle, repeat,\n groupby, accumulate, combinations, permutations,\n product, zip_longest, tee, filterfalse\n)\n\n# Chain multiple iterables\ncombined = list(chain([1, 2], [3, 4], [5, 6])) # [1,2,3,4,5,6]\n\n# Slice iterator (memory efficient)\nfirst_10 = list(islice(range(1000), 10))\n\n# Infinite iterators\nfrom itertools import count\ncounter = count(start=1, step=2) # 1, 3, 5, 7, ...\n\n# Groupby for grouping\ndata = [(\"A\", 1), (\"A\", 2), (\"B\", 1), (\"B\", 2)]\ngrouped = {k: list(v) for k, v in groupby(data, key=lambda x: x[0])}\n\n# Accumulate for running totals\ncumsum = list(accumulate([1, 2, 3, 4, 5])) # [1, 3, 6, 10, 15]\n\n# Combinations and permutations\ncombos = list(combinations([1, 2, 3], 2)) # [(1,2), (1,3), (2,3)]\nperms = list(permutations([1, 2, 3], 2)) # [(1,2), (1,3), (2,1), ...]\n\n# Cartesian product\npairs = list(product([1, 2], ['a', 'b'])) # [(1,'a'), (1,'b'), (2,'a'), (2,'b')]\n\n# Zip with different lengths\nfrom itertools import zip_longest\npaired = list(zip_longest([1, 2], ['a', 'b', 'c'], fillvalue=0))\n\n# Tee for multiple iterators\nit1, it2 = tee(range(5), 2)\n\n# Filter false\nodds = list(filterfalse(lambda x: x % 2 == 0, range(10)))\n```\n\n## Collections for Data Structures\n\n```python\nfrom collections import (\n defaultdict, Counter, deque, namedtuple,\n ChainMap, OrderedDict\n)\n\n# defaultdict for automatic defaults\nword_index: defaultdict[str, list[int]] = defaultdict(list)\nfor i, word in enumerate([\"hello\", \"world\", \"hello\"]):\n word_index[word].append(i)\n\n# Counter for counting\nfrom collections import Counter\n\nword_counts = Counter([\"apple\", \"banana\", \"apple\", \"cherry\", \"banana\", \"apple\"])\nprint(word_counts.most_common(2)) # [('apple', 3), ('banana', 2)]\n\n# Counter operations\nc1 = Counter(a=3, b=1)\nc2 = Counter(a=1, b=2)\nprint(c1 + c2) # Counter({'a': 4, 'b': 3})\n\n# deque for efficient queue operations\nfrom collections import deque\n\nqueue: deque[str] = deque()\nqueue.append(\"first\")\nqueue.append(\"second\")\nqueue.appendleft(\"priority\")\nitem = queue.popleft() # \"priority\"\n\n# Ring buffer with maxlen\nrecent: deque[int] = deque(maxlen=3)\nfor i in range(5):\n recent.append(i) # Only keeps last 3\n\n# namedtuple for lightweight classes\nfrom collections import namedtuple\n\nPoint = namedtuple('Point', ['x', 'y'])\np = Point(1, 2)\nprint(p.x, p.y)\n\n# ChainMap for layered configs\nfrom collections import ChainMap\n\ndefaults = {'color': 'red', 'user': 'guest'}\nenvironment = {'user': 'admin'}\ncombined = ChainMap(environment, defaults)\nprint(combined['user']) # 'admin' (from environment)\n```\n\n## Context Managers\n\n```python\nfrom contextlib import contextmanager, suppress, ExitStack\n\n# Custom context manager\n@contextmanager\ndef managed_resource(resource_id: str) -> Iterator[Resource]:\n resource = acquire_resource(resource_id)\n try:\n yield resource\n finally:\n release_resource(resource)\n\n# Suppress exceptions\nwith suppress(FileNotFoundError):\n Path(\"nonexistent.txt\").unlink()\n\n# ExitStack for dynamic context managers\ndef process_files(filenames: list[str]) -> None:\n with ExitStack() as stack:\n files = [stack.enter_context(open(fn)) for fn in filenames]\n # All files auto-closed on exit\n for f in files:\n process(f.read())\n```\n\n## Enum for Constants\n\n```python\nfrom enum import Enum, auto, IntEnum, Flag\n\n# Basic enum\nclass Status(Enum):\n PENDING = \"pending\"\n APPROVED = \"approved\"\n REJECTED = \"rejected\"\n\n# Auto values\nclass Color(Enum):\n RED = auto()\n GREEN = auto()\n BLUE = auto()\n\n# IntEnum for numeric values\nclass Priority(IntEnum):\n LOW = 1\n MEDIUM = 2\n HIGH = 3\n\n# Flag for bit flags\nclass Permission(Flag):\n READ = auto()\n WRITE = auto()\n EXECUTE = auto()\n\nuser_perms = Permission.READ | Permission.WRITE\nif Permission.READ in user_perms:\n print(\"Can read\")\n```\n\n## Logging\n\n```python\nimport logging\nfrom pathlib import Path\n\n# Configure logging\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n handlers=[\n logging.FileHandler('app.log'),\n logging.StreamHandler()\n ]\n)\n\nlogger = logging.getLogger(__name__)\n\n# Structured logging\ndef process_user(user_id: int) -> None:\n logger.info(\"Processing user\", extra={\"user_id\": user_id})\n try:\n # Process...\n logger.debug(\"User data loaded\", extra={\"user_id\": user_id})\n except Exception as e:\n logger.exception(\"Failed to process user\", extra={\"user_id\": user_id})\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":9063,"content_sha256":"d2997c8f9a491561947c95a182e09b2d584d828d26cb04eb42a194fa4393c6ce"},{"filename":"references/testing.md","content":"# Testing with Pytest\n\n## Basic Pytest Structure\n\n```python\n# test_user.py\nimport pytest\nfrom myapp.user import User, UserService\n\n# Simple test function\ndef test_user_creation() -> None:\n user = User(id=1, name=\"Alice\", email=\"[email protected]\")\n assert user.name == \"Alice\"\n assert user.is_active is True\n\n# Test with multiple assertions\ndef test_user_validation() -> None:\n with pytest.raises(ValueError, match=\"Invalid email\"):\n User(id=1, name=\"Alice\", email=\"invalid\")\n\n# Test class for grouping\nclass TestUserService:\n def test_find_user(self) -> None:\n service = UserService()\n user = service.find(1)\n assert user is not None\n\n def test_create_user(self) -> None:\n service = UserService()\n user = service.create(name=\"Bob\", email=\"[email protected]\")\n assert user.id > 0\n```\n\n## Fixtures for Setup/Teardown\n\n```python\n# conftest.py - shared fixtures\nimport pytest\nfrom typing import Iterator\nfrom myapp.database import Database, Session\n\[email protected]\ndef db() -> Iterator[Database]:\n \"\"\"Provide database instance with cleanup.\"\"\"\n database = Database(\"test.db\")\n database.create_tables()\n yield database\n database.drop_tables()\n database.close()\n\[email protected]\ndef db_session(db: Database) -> Iterator[Session]:\n \"\"\"Provide database session with rollback.\"\"\"\n session = db.create_session()\n yield session\n session.rollback()\n session.close()\n\[email protected]\ndef sample_user() -> User:\n \"\"\"Provide test user.\"\"\"\n return User(id=1, name=\"Test User\", email=\"[email protected]\")\n\n# Using fixtures in tests\ndef test_user_creation(db_session: Session, sample_user: User) -> None:\n db_session.add(sample_user)\n db_session.commit()\n\n retrieved = db_session.query(User).filter_by(id=1).first()\n assert retrieved.name == \"Test User\"\n\n# Fixture with parameters\[email protected](params=[\"sqlite\", \"postgresql\", \"mysql\"])\ndef db_engine(request: pytest.FixtureRequest) -> str:\n return request.param\n\ndef test_connection(db_engine: str) -> None:\n # Test runs 3 times with different engines\n assert create_connection(db_engine)\n\n# Autouse fixture (runs automatically)\[email protected](autouse=True)\ndef reset_state() -> Iterator[None]:\n \"\"\"Reset global state before each test.\"\"\"\n clear_caches()\n yield\n cleanup_temp_files()\n```\n\n## Parametrize for Multiple Cases\n\n```python\nimport pytest\n\n# Parametrize test function\[email protected](\n \"input,expected\",\n [\n (2, 4),\n (3, 9),\n (4, 16),\n (-2, 4),\n ]\n)\ndef test_square(input: int, expected: int) -> None:\n assert square(input) == expected\n\n# Multiple parameters\[email protected](\"base\", [2, 10])\[email protected](\"exponent\", [0, 1, 2])\ndef test_power(base: int, exponent: int) -> None:\n result = base ** exponent\n assert result >= 0\n\n# Parametrize with IDs\[email protected](\n \"email,valid\",\n [\n (\"[email protected]\", True),\n (\"invalid\", False),\n (\"@example.com\", False),\n (\"user@\", False),\n ],\n ids=[\"valid\", \"no_at\", \"no_user\", \"no_domain\"]\n)\ndef test_email_validation(email: str, valid: bool) -> None:\n assert is_valid_email(email) == valid\n\n# Parametrize with fixtures\[email protected]\ndef user_factory():\n def _make_user(name: str, active: bool = True) -> User:\n return User(name=name, active=active)\n return _make_user\n\[email protected](\"name\", [\"Alice\", \"Bob\", \"Charlie\"])\ndef test_user_names(user_factory, name: str) -> None:\n user = user_factory(name)\n assert user.name == name\n```\n\n## Mocking and Patching\n\n```python\nfrom unittest.mock import Mock, MagicMock, patch, AsyncMock, call\nimport pytest\n\n# Mock object\ndef test_api_call_with_mock() -> None:\n mock_client = Mock()\n mock_client.get.return_value = {\"status\": \"ok\"}\n\n service = ApiService(mock_client)\n result = service.fetch_data()\n\n mock_client.get.assert_called_once_with(\"/api/data\")\n assert result[\"status\"] == \"ok\"\n\n# Patch function/method\ndef test_database_call() -> None:\n with patch(\"myapp.database.connect\") as mock_connect:\n mock_connect.return_value = Mock()\n\n db = Database()\n db.connect()\n\n mock_connect.assert_called_once()\n\n# Patch as decorator\n@patch(\"myapp.user.send_email\")\ndef test_user_registration(mock_send_email: Mock) -> None:\n service = UserService()\n service.register(\"[email protected]\")\n\n mock_send_email.assert_called_with(\n to=\"[email protected]\",\n subject=\"Welcome\"\n )\n\n# Multiple patches\n@patch(\"myapp.api.requests.get\")\n@patch(\"myapp.api.cache.get\")\ndef test_cached_api(mock_cache: Mock, mock_requests: Mock) -> None:\n mock_cache.return_value = None\n mock_requests.return_value.json.return_value = {\"data\": \"value\"}\n\n result = fetch_with_cache(\"key\")\n\n mock_cache.assert_called_once_with(\"key\")\n mock_requests.assert_called_once()\n\n# Mock side effects\ndef test_retry_logic() -> None:\n mock_api = Mock()\n mock_api.call.side_effect = [\n ConnectionError(\"Failed\"),\n ConnectionError(\"Failed\"),\n {\"status\": \"ok\"}\n ]\n\n result = retry_api_call(mock_api)\n assert result[\"status\"] == \"ok\"\n assert mock_api.call.call_count == 3\n\n# Async mock\[email protected]\nasync def test_async_function() -> None:\n mock_db = AsyncMock()\n mock_db.fetch_user.return_value = User(id=1, name=\"Alice\")\n\n service = AsyncUserService(mock_db)\n user = await service.get_user(1)\n\n mock_db.fetch_user.assert_awaited_once_with(1)\n assert user.name == \"Alice\"\n```\n\n## Async Testing\n\n```python\nimport pytest\nimport asyncio\n\n# Mark async test\[email protected]\nasync def test_async_fetch() -> None:\n result = await fetch_data(\"https://api.example.com\")\n assert result[\"status\"] == \"ok\"\n\n# Async fixture\[email protected]\nasync def async_db() -> AsyncIterator[AsyncDatabase]:\n db = AsyncDatabase()\n await db.connect()\n yield db\n await db.disconnect()\n\[email protected]\nasync def test_async_query(async_db: AsyncDatabase) -> None:\n result = await async_db.query(\"SELECT * FROM users\")\n assert len(result) > 0\n\n# Test concurrent operations\[email protected]\nasync def test_concurrent_requests() -> None:\n urls = [\"http://example.com/1\", \"http://example.com/2\"]\n results = await asyncio.gather(*[fetch(url) for url in urls])\n assert len(results) == 2\n```\n\n## Pytest Markers\n\n```python\nimport pytest\n\n# Skip test\[email protected](reason=\"Not implemented yet\")\ndef test_future_feature() -> None:\n pass\n\n# Conditional skip\[email protected](sys.version_info \u003c (3, 11), reason=\"Requires Python 3.11+\")\ndef test_new_feature() -> None:\n pass\n\n# Expected failure\[email protected](reason=\"Known bug #123\")\ndef test_known_bug() -> None:\n assert buggy_function() == expected_value\n\n# Custom markers\[email protected]\ndef test_slow_operation() -> None:\n time.sleep(5)\n assert True\n\[email protected]\ndef test_integration() -> None:\n assert external_service.ping()\n\n# Run with: pytest -m \"not slow\"\n```\n\n## Test Coverage\n\n```python\n# Run with coverage\n# pytest --cov=myapp --cov-report=html --cov-report=term\n\n# conftest.py - coverage configuration\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\", \"unit: mark test as unit test\"\n )\n\n# pytest.ini or pyproject.toml\n\"\"\"\n[tool.pytest.ini_options]\nminversion = \"7.0\"\naddopts = [\n \"--cov=myapp\",\n \"--cov-report=term-missing\",\n \"--cov-fail-under=90\",\n \"-ra\",\n \"--strict-markers\",\n]\ntestpaths = [\"tests\"]\n\"\"\"\n```\n\n## Property-Based Testing\n\n```python\nfrom hypothesis import given, strategies as st\n\n# Property-based test\n@given(st.integers(), st.integers())\ndef test_addition_commutative(a: int, b: int) -> None:\n assert a + b == b + a\n\n@given(st.lists(st.integers()))\ndef test_sorted_is_ordered(lst: list[int]) -> None:\n sorted_lst = sorted(lst)\n for i in range(len(sorted_lst) - 1):\n assert sorted_lst[i] \u003c= sorted_lst[i + 1]\n\n# Custom strategies\n@given(st.emails())\ndef test_email_validation(email: str) -> None:\n assert \"@\" in email\n assert validate_email(email)\n\n# Composite strategies\nfrom hypothesis import strategies as st\nfrom hypothesis.strategies import composite\n\n@composite\ndef users(draw) -> User:\n return User(\n id=draw(st.integers(min_value=1)),\n name=draw(st.text(min_size=1, max_size=50)),\n email=draw(st.emails()),\n age=draw(st.integers(min_value=18, max_value=120))\n )\n\n@given(users())\ndef test_user_creation(user: User) -> None:\n assert user.age >= 18\n assert len(user.name) > 0\n```\n\n## Test Organization\n\n```python\n# tests/\n# conftest.py - Shared fixtures\n# test_user.py - User tests\n# test_api.py - API tests\n# integration/\n# test_workflow.py - Integration tests\n# unit/\n# test_models.py - Unit tests\n\n# Fixture factory pattern\[email protected]\ndef user_factory(db_session: Session):\n created_users: list[User] = []\n\n def _create_user(\n name: str = \"Test User\",\n email: str | None = None,\n **kwargs\n ) -> User:\n if email is None:\n email = f\"{name.lower().replace(' ', '.')}@example.com\"\n\n user = User(name=name, email=email, **kwargs)\n db_session.add(user)\n db_session.commit()\n created_users.append(user)\n return user\n\n yield _create_user\n\n # Cleanup\n for user in created_users:\n db_session.delete(user)\n db_session.commit()\n```\n\n## Snapshot Testing\n\n```python\nimport pytest\nfrom syrupy.assertion import SnapshotAssertion\n\ndef test_api_response(snapshot: SnapshotAssertion) -> None:\n response = api.get_user(1)\n assert response == snapshot\n\ndef test_rendered_template(snapshot: SnapshotAssertion) -> None:\n html = render_template(\"user.html\", user=get_user(1))\n assert html == snapshot\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":9920,"content_sha256":"81c8bc148eaf7d32e51171c997016c7deda140b71d6253b15b63b10f038f3c28"},{"filename":"references/type-system.md","content":"# Type System Mastery\n\n## Basic Type Annotations\n\n```python\nfrom typing import Any\nfrom collections.abc import Sequence, Mapping\n\n# Function signatures\ndef process_user(name: str, age: int, active: bool = True) -> dict[str, Any]:\n return {\"name\": name, \"age\": age, \"active\": active}\n\n# Use | for unions (Python 3.10+)\ndef find_user(user_id: int | str) -> dict[str, Any] | None:\n if isinstance(user_id, int):\n return {\"id\": user_id}\n return None\n\n# Collections - prefer collections.abc\ndef process_items(items: Sequence[str]) -> list[str]:\n \"\"\"Accepts list, tuple, or any sequence.\"\"\"\n return [item.upper() for item in items]\n\ndef merge_configs(base: Mapping[str, int], override: dict[str, int]) -> dict[str, int]:\n \"\"\"Mapping for read-only, dict for mutable.\"\"\"\n return {**base, **override}\n```\n\n## Generic Types\n\n```python\nfrom typing import TypeVar, Generic, Protocol\nfrom collections.abc import Callable\n\nT = TypeVar('T')\nK = TypeVar('K')\nV = TypeVar('V')\n\n# Generic function\ndef first_element(items: Sequence[T]) -> T | None:\n return items[0] if items else None\n\n# Generic class\nclass Cache(Generic[K, V]):\n def __init__(self) -> None:\n self._data: dict[K, V] = {}\n\n def get(self, key: K) -> V | None:\n return self._data.get(key)\n\n def set(self, key: K, value: V) -> None:\n self._data[key] = value\n\n# Usage\nuser_cache: Cache[int, str] = Cache()\nuser_cache.set(1, \"Alice\")\n\n# Constrained TypeVar\nfrom numbers import Number\nNumT = TypeVar('NumT', bound=Number)\n\ndef add_numbers(a: NumT, b: NumT) -> NumT:\n return a + b # type: ignore[return-value]\n```\n\n## Protocol for Structural Typing\n\n```python\nfrom typing import Protocol, runtime_checkable\n\n# Define interface without inheritance\nclass Drawable(Protocol):\n def draw(self) -> str:\n ...\n\n @property\n def color(self) -> str:\n ...\n\nclass Circle:\n def __init__(self, radius: float, color: str) -> None:\n self.radius = radius\n self._color = color\n\n def draw(self) -> str:\n return f\"Drawing {self._color} circle\"\n\n @property\n def color(self) -> str:\n return self._color\n\n# Circle implements Drawable without inheriting\ndef render(shape: Drawable) -> str:\n return shape.draw()\n\n# Runtime checkable protocol\n@runtime_checkable\nclass Closeable(Protocol):\n def close(self) -> None:\n ...\n\ndef cleanup(resource: Closeable) -> None:\n if isinstance(resource, Closeable):\n resource.close()\n```\n\n## Advanced Type Features\n\n```python\nfrom typing import Literal, TypeAlias, TypedDict, NotRequired, Self, overload\n\n# Literal types for constants\nMode = Literal[\"read\", \"write\", \"append\"]\n\ndef open_file(path: str, mode: Mode) -> None:\n ...\n\n# Type aliases for complex types\nJsonDict: TypeAlias = dict[str, Any]\nUserId: TypeAlias = int | str\n\n# TypedDict for structured dictionaries\nclass UserDict(TypedDict):\n id: int\n name: str\n email: str\n age: NotRequired[int] # Optional field\n\ndef create_user(data: UserDict) -> None:\n print(data[\"name\"]) # Type-safe access\n\n# Self type for method chaining\nclass Builder:\n def __init__(self) -> None:\n self._value = 0\n\n def add(self, n: int) -> Self:\n self._value += n\n return self\n\n def multiply(self, n: int) -> Self:\n self._value *= n\n return self\n\n# Overload for different signatures\n@overload\ndef process(data: str) -> str: ...\n\n@overload\ndef process(data: int) -> int: ...\n\ndef process(data: str | int) -> str | int:\n if isinstance(data, str):\n return data.upper()\n return data * 2\n```\n\n## Callable Types\n\n```python\nfrom collections.abc import Callable\nfrom typing import ParamSpec, Concatenate\n\n# Basic callable\ndef apply(func: Callable[[int, int], int], a: int, b: int) -> int:\n return func(a, b)\n\n# ParamSpec for preserving signatures\nP = ParamSpec('P')\nR = TypeVar('R')\n\ndef logging_decorator(func: Callable[P, R]) -> Callable[P, R]:\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n print(f\"Calling {func.__name__}\")\n return func(*args, **kwargs)\n return wrapper\n\n# Concatenate for dependency injection\ndef with_connection(\n func: Callable[Concatenate[Connection, P], R]\n) -> Callable[P, R]:\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n conn = get_connection()\n return func(conn, *args, **kwargs)\n return wrapper\n\n# Usage\n@with_connection\ndef query_user(conn: Connection, user_id: int) -> User:\n return conn.execute(f\"SELECT * FROM users WHERE id = {user_id}\")\n```\n\n## Mypy Configuration\n\n```toml\n# pyproject.toml\n[tool.mypy]\npython_version = \"3.11\"\nstrict = true\nwarn_return_any = true\nwarn_unused_configs = true\ndisallow_untyped_defs = true\ndisallow_any_generics = true\ndisallow_subclassing_any = true\ndisallow_untyped_calls = true\ndisallow_incomplete_defs = true\ncheck_untyped_defs = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_unused_ignores = true\nwarn_no_return = true\nwarn_unreachable = true\nstrict_equality = true\n\n[[tool.mypy.overrides]]\nmodule = \"third_party.*\"\nignore_missing_imports = true\n```\n\n## Common Type Patterns\n\n```python\n# Result type pattern\nfrom dataclasses import dataclass\n\n@dataclass\nclass Success(Generic[T]):\n value: T\n\n@dataclass\nclass Error:\n message: str\n\nResult = Success[T] | Error\n\ndef divide(a: int, b: int) -> Result[float]:\n if b == 0:\n return Error(\"Division by zero\")\n return Success(a / b)\n\n# Option/Maybe type\ndef safe_get(items: Sequence[T], index: int) -> T | None:\n try:\n return items[index]\n except IndexError:\n return None\n\n# Sentinel value with typing\nfrom typing import Final\n\nMISSING: Final = object()\n\ndef get_value(key: str, default: T | type[MISSING] = MISSING) -> T:\n if default is MISSING:\n raise KeyError(key)\n return default # type: ignore[return-value]\n```\n\n## Type Narrowing\n\n```python\nfrom typing import assert_type, assert_never\n\ndef process_value(value: int | str | None) -> str:\n # Type guards\n if value is None:\n return \"null\"\n\n if isinstance(value, int):\n # Type narrowed to int\n return str(value * 2)\n\n # Type narrowed to str\n return value.upper()\n\n# Exhaustiveness checking\ndef handle_mode(mode: Literal[\"read\", \"write\"]) -> str:\n if mode == \"read\":\n return \"Reading\"\n elif mode == \"write\":\n return \"Writing\"\n else:\n # Mypy will error if mode can be anything else\n assert_never(mode)\n\n# Custom type guard\ndef is_string_list(val: list[Any]) -> bool:\n \"\"\"Runtime check for list of strings.\"\"\"\n return all(isinstance(x, str) for x in val)\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":6638,"content_sha256":"62c4474c4ed29a18fd64002a356cba0239785f68c8530109c74c5bb3162b021b"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Python Pro","type":"text"}]},{"type":"paragraph","content":[{"text":"Modern Python 3.11+ specialist focused on type-safe, async-first, production-ready code.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Use This Skill","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Writing type-safe Python with complete type coverage","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implementing async/await patterns for I/O operations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Setting up pytest test suites with fixtures and mocking","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Creating Pythonic code with comprehensions, generators, context managers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Building packages with Poetry and proper project structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Performance optimization and profiling","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core Workflow","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Analyze codebase","type":"text","marks":[{"type":"strong"}]},{"text":" — Review structure, dependencies, type coverage, test suite","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design interfaces","type":"text","marks":[{"type":"strong"}]},{"text":" — Define protocols, dataclasses, type aliases","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement","type":"text","marks":[{"type":"strong"}]},{"text":" — Write Pythonic code with full type hints and error handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Test","type":"text","marks":[{"type":"strong"}]},{"text":" — Create comprehensive pytest suite with >90% coverage","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate","type":"text","marks":[{"type":"strong"}]},{"text":" — Run ","type":"text"},{"text":"mypy --strict","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"black","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"ruff","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If mypy fails: fix type errors reported and re-run before proceeding","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If tests fail: debug assertions, update fixtures, and iterate until green","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If ruff/black reports issues: apply auto-fixes, then re-validate","type":"text"}]}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Reference Guide","type":"text"}]},{"type":"paragraph","content":[{"text":"Load detailed guidance based on context:","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Topic","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Reference","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Load When","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Type System","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/type-system.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Type hints, mypy, generics, Protocol","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Async Patterns","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/async-patterns.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"async/await, asyncio, task groups","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Standard Library","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/standard-library.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"pathlib, dataclasses, functools, itertools","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Testing","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/testing.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"pytest, fixtures, mocking, parametrize","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Packaging","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/packaging.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"poetry, pip, pyproject.toml, distribution","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Constraints","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"MUST DO","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Type hints for all function signatures and class attributes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"PEP 8 compliance with black formatting","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Comprehensive docstrings (Google style)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Test coverage exceeding 90% with pytest","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use ","type":"text"},{"text":"X | None","type":"text","marks":[{"type":"code_inline"}]},{"text":" instead of ","type":"text"},{"text":"Optional[X]","type":"text","marks":[{"type":"code_inline"}]},{"text":" (Python 3.10+)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Async/await for I/O-bound operations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Dataclasses over manual ","type":"text"},{"text":"init","type":"text","marks":[{"type":"underline"}]},{"text":" methods","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Context managers for resource handling","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"MUST NOT DO","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Skip type annotations on public APIs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use mutable default arguments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mix sync and async code improperly","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Ignore mypy errors in strict mode","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use bare except clauses","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Hardcode secrets or configuration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use deprecated stdlib modules (use pathlib not os.path)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Code Examples","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Type-annotated function with error handling","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"from pathlib import Path\n\ndef read_config(path: Path) -> dict[str, str]:\n \"\"\"Read configuration from a file.\n\n Args:\n path: Path to the configuration file.\n\n Returns:\n Parsed key-value configuration entries.\n\n Raises:\n FileNotFoundError: If the config file does not exist.\n ValueError: If a line cannot be parsed.\n \"\"\"\n config: dict[str, str] = {}\n with path.open() as f:\n for line in f:\n key, _, value = line.partition(\"=\")\n if not key.strip():\n raise ValueError(f\"Invalid config line: {line!r}\")\n config[key.strip()] = value.strip()\n return config","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Dataclass with validation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"from dataclasses import dataclass, field\n\n@dataclass\nclass AppConfig:\n host: str\n port: int\n debug: bool = False\n allowed_origins: list[str] = field(default_factory=list)\n\n def __post_init__(self) -> None:\n if not (1 \u003c= self.port \u003c= 65535):\n raise ValueError(f\"Invalid port: {self.port}\")","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Async pattern","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import asyncio\nimport httpx\n\nasync def fetch_all(urls: list[str]) -> list[bytes]:\n \"\"\"Fetch multiple URLs concurrently.\"\"\"\n async with httpx.AsyncClient() as client:\n tasks = [client.get(url) for url in urls]\n responses = await asyncio.gather(*tasks)\n return [r.content for r in responses]","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"pytest fixture and parametrize","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import pytest\nfrom pathlib import Path\n\[email protected]\ndef config_file(tmp_path: Path) -> Path:\n cfg = tmp_path / \"config.txt\"\n cfg.write_text(\"host=localhost\\nport=8080\\n\")\n return cfg\n\[email protected](\"port,valid\", [(8080, True), (0, False), (99999, False)])\ndef test_app_config_port_validation(port: int, valid: bool) -> None:\n if valid:\n AppConfig(host=\"localhost\", port=port)\n else:\n with pytest.raises(ValueError):\n AppConfig(host=\"localhost\", port=port)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"mypy strict configuration (pyproject.toml)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"toml"},"content":[{"text":"[tool.mypy]\npython_version = \"3.11\"\nstrict = true\nwarn_return_any = true\nwarn_unused_configs = true\ndisallow_untyped_defs = true","type":"text"}]},{"type":"paragraph","content":[{"text":"Clean ","type":"text"},{"text":"mypy --strict","type":"text","marks":[{"type":"code_inline"}]},{"text":" output looks like:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Success: no issues found in 12 source files","type":"text"}]},{"type":"paragraph","content":[{"text":"Any reported error (e.g., ","type":"text"},{"text":"error: Function is missing a return type annotation","type":"text","marks":[{"type":"code_inline"}]},{"text":") must be resolved before the implementation is considered complete.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Output Templates","type":"text"}]},{"type":"paragraph","content":[{"text":"When implementing Python features, provide:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Module file with complete type hints","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Test file with pytest fixtures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Type checking confirmation (mypy --strict passes)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Brief explanation of Pythonic patterns used","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Knowledge Reference","type":"text"}]},{"type":"paragraph","content":[{"text":"Python 3.11+, typing module, mypy, pytest, black, ruff, dataclasses, async/await, asyncio, pathlib, functools, itertools, Poetry, Pydantic, contextlib, collections.abc, Protocol","type":"text"}]},{"type":"paragraph","content":[{"text":"Maintained by ","type":"text"},{"text":"@jeffallan","type":"text","marks":[{"type":"link","attrs":{"href":"https://github.com/jeffallan","title":null}}]},{"text":", Principal Consultant at ","type":"text"},{"text":"Synergetic Solutions","type":"text","marks":[{"type":"link","attrs":{"href":"https://synergetic.solutions","title":null}}]}]},{"type":"paragraph","content":[{"text":"Documentation","type":"text","marks":[{"type":"link","attrs":{"href":"https://jeffallan.github.io/claude-skills/skills/language/python-pro/","title":null}}]}]}]},"metadata":{"date":"2026-11-02","name":"python-pro","author":"@skillopedia","source":{"stars":12181,"repo_name":"claude-skills","origin_url":"https://github.com/Jeffallan/claude-skills/blob/HEAD/skills/python-pro/SKILL.md","repo_owner":"Jeffallan","body_sha256":"b94b59450d7372ac0cf47c7313a189796a5a7b0470552b2fe9e9581ec6c3de04","cluster_key":"c1a9e502b699d7cec832312d2a5bd4e364fb6bff8ae0cfff95f2cef46b2476a6","clean_bundle":{"format":"clean-skill-bundle-v1","source":"Jeffallan/claude-skills/skills/python-pro/SKILL.md","text_bytes":44606,"source_commit":"078a25cc5bfd8011459be7b91d004e900c1d02d3","skills_sh_rank":2754,"attachment_count":5,"text_attachments":5,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"skills/python-pro/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"software-engineering","category_label":"Engineering"},"exact_dupes_collapsed_into_this":0},"license":"MIT","version":"v1","category":"software-engineering","metadata":{"role":"specialist","scope":"implementation","author":"https://github.com/Jeffallan","domain":"language","company":"https://synergetic.solutions","version":"1.1.0","triggers":"Python development, type hints, async Python, pytest, mypy, dataclasses, Python best practices, Pythonic code","output-format":"code","related-skills":"fastapi-expert, devops-engineer"},"import_tag":"skills-sh-top20k-2026-11","description":"Use when building Python 3.11+ applications requiring type safety, async programming, or robust error handling. Generates type-annotated Python code, configures mypy in strict mode, writes pytest test suites with fixtures and mocking, and validates code with black and ruff. Invoke for type hints, async/await patterns, dataclasses, dependency injection, logging configuration, and structured error handling."}},"renderedAt":1793671242394}

Python Pro Modern Python 3.11+ specialist focused on type-safe, async-first, production-ready code. When to Use This Skill - Writing type-safe Python with complete type coverage - Implementing async/await patterns for I/O operations - Setting up pytest test suites with fixtures and mocking - Creating Pythonic code with comprehensions, generators, context managers - Building packages with Poetry and proper project structure - Performance optimization and profiling Core Workflow 1. Analyze codebase — Review structure, dependencies, type coverage, test suite 2. Design interfaces — Define protoco…