Quick Start
Prerequisites:
- Python 3.10+ installed (
python --version)
- Dependency manager: uv (recommended), poetry, or pip+venv
- IDE with Python language server (VS Code, PyCharm)
Tools Used: Read, Write, Edit, Bash (for uv/poetry/pip commands), LSP diagnostics
Dependency Management Decision Tree:
New project? → Use uv: uv init, uv add, uv sync
Existing poetry? → Use poetry: poetry install, poetry add
Legacy/simple? → Use pip+venv: python -m venv, pip install
Basic Usage:
- Set up environment (see decision tree)
- Write code with type hints
- Write tests first (TDD)
- Run tests:
pytest
- Verify types:
mypy .
What I Do
- Create Python 3.10+ applications (data science, backend, scripting, automation)
- Manage dependencies with uv, poetry, or pip
- Implement type hints (typing module, generics, protocols)
- Write tests with pytest (fixtures, parametrize, mocking)
- Work with pandas DataFrames (selection, groupby, merge)
- Use Python patterns (decorators, comprehensions, generators, dataclasses)
- Handle errors with logging integration
- Follow TDD workflow (Red-Green-Refactor)
When to Use Me
Use this skill when you:
- Create, refactor, or debug Python 3.10+ code
- Set up projects with dependency management (uv, poetry, pip)
- Implement type hints or fix type errors
- Write pytest tests (fixtures, parametrize, mocking)
- Work with pandas DataFrames
- Use Python patterns (decorators, generators, dataclasses)
- Handle errors with logging
- Follow TDD workflows
Python Version Features
| Version |
Features |
| 3.10 |
Pattern matching, union types (|), TypeAlias |
| 3.11 |
Exception groups (except*), Self type |
| 3.12 |
Type parameters (def func[T]), f-string improvements |
Quick Reference Tables
Built-in Functions
| Function |
Purpose |
map(func, iterable) |
Apply function to each item |
filter(func, iterable) |
Keep items where condition is True |
zip(*iterables) |
Combine iterables element-wise |
enumerate(iterable) |
Add index to iterable |
String Operations
| Operation |
Example |
| f-strings |
f"Hello {name}" |
.join() |
", ".join(['a', 'b']) |
.split() |
"a,b".split(",") |
Collection Methods
| Type |
Common Methods |
| list |
.append(), .extend(), .pop(), .sort() |
| dict |
.get(), .keys(), .values(), .items() |
| set |
.add(), .remove(), .union() |
Type Hints Basics
from typing import Optional
def greet(name: str) -> str:
return f"Hello {name}"
def process_items(items: list[int]) -> dict[str, int]:
return {"count": len(items), "sum": sum(items)}
def find_user(user_id: int) -> Optional[str]:
return users.get(user_id)
def parse_value(val: str | int) -> int: # Python 3.10+
return int(val)
See references/type-hints.md for Generics and Protocols.
TDD Workflow (Red-Green-Refactor)
- Red: Write failing test
- Green: Write minimal code to pass
- Refactor: Improve while keeping tests green
# Red: Test fails (function doesn't exist)
def test_total():
assert calculate_total([10, 20, 30]) == 60
# Green: Make it pass
def calculate_total(items):
return sum(items)
# Refactor: Add types and edge cases
def calculate_total(items: list[int]) -> int:
return sum(items) if items else 0
See references/pytest.md for fixtures and mocking.
Error Handling with Logging
import logging
logger = logging.getLogger(__name__)
# Try/Except/Finally
try:
result = risky_operation()
except ValueError as e:
logger.error(f"Invalid value: {e}")
raise
finally:
cleanup_resources()
# Custom Exceptions
class DataValidationError(Exception):
pass
def validate_data(data: dict) -> None:
if "required_field" not in data:
raise DataValidationError("required_field missing")
# Context Manager for cleanup
from contextlib import contextmanager
@contextmanager
def db_connection(url: str):
conn = connect(url)
try:
yield conn
finally:
conn.close()
Examples
Example 1: Dataclass with Type Hints
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class User:
id: int
name: str
email: str
tags: List[str] = None
def __post_init__(self):
if self.tags is None:
self.tags = []
# Usage
user = User(id=1, name="Alice", email="alice@example.com")
user.tags.append("admin")
Example 2: Decorator Pattern
import functools
import time
import logging
logger = logging.getLogger(__name__)
def timing_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
logger.info(f"{func.__name__} took {elapsed:.2f}s")
return result
return wrapper
@timing_decorator
def slow_function():
time.sleep(1)
return "done"
Example 3: List Comprehension with Filtering
# Filter and transform in one line
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [x**2 for x in numbers if x % 2 == 0]
# Result: [4, 16, 36]
# Dict comprehension
users = [("alice", 25), ("bob", 30)]
user_dict = {name: age for name, age in users}
# Result: {"alice": 25, "bob": 30}
Example 4: Generator for Memory Efficiency
def read_large_file(file_path: str):
with open(file_path, 'r') as f:
for line in f:
yield line.strip()
for line in read_large_file("huge.txt"):
process(line)
See references/patterns.md for more patterns.
Common Errors
| Error |
Solution |
ModuleNotFoundError |
Run uv add <package> or pip install <package> |
TypeError |
Check types, add type hints |
KeyError |
Use .get('key', default) instead of ['key'] |
IndentationError |
Use 4 spaces (PEP 8) |
AttributeError: 'NoneType' |
Check for None: if obj is not None: |
Related Skills
- pytest-testing: Fixtures, parametrize, mocking
- pandas-data-analysis: Advanced DataFrame operations
- fastapi-backend: REST APIs with FastAPI
- django-web: Web applications with Django
- github-actions: CI/CD for Python
References
- references/patterns.md - Context managers, decorators, comprehensions, generators, dataclasses, async/await
- references/type-hints.md - Advanced typing (Generics, Protocols, TypeVar, type guards)
- references/pytest.md - Fixtures, parametrize, mocking, assertions
- references/pandas.md - DataFrame operations, groupby, merge, performance
- references/dependency-management.md - uv, poetry, pip workflows and pyproject.toml
1---2name: python-core3description: Create, write, build, debug, test, refactor, and optimize Python 3.10+ applications across all domains (data science, backend APIs, scripting, automation). Manage dependencies with uv (preferred), poetry, or pip. Implement type hints (typing module, generics, protocols), write tests with pytest (fixtures, parametrize, mocking), work with pandas DataFrames (creation, selection, groupby, merge), use dataclasses and decorators, handle errors with logging integration, and follow TDD workflows (Red-Green-Refactor). Configure virtual environments, pyproject.toml, and static analysis tools (mypy, pyright). Use when implementing Python features, fixing bugs, writing tests, managing packages, analyzing data, or building Python projects.4license: MIT5---67## Quick Start89**Prerequisites:**10- Python 3.10+ installed (`python --version`)11- Dependency manager: uv (recommended), poetry, or pip+venv12- IDE with Python language server (VS Code, PyCharm)1314**Tools Used:** Read, Write, Edit, Bash (for uv/poetry/pip commands), LSP diagnostics1516**Dependency Management Decision Tree:**17```18New project? → Use uv: uv init, uv add, uv sync19Existing poetry? → Use poetry: poetry install, poetry add20Legacy/simple? → Use pip+venv: python -m venv, pip install21```2223**Basic Usage:**241. Set up environment (see decision tree)252. Write code with type hints263. Write tests first (TDD)274. Run tests: `pytest`285. Verify types: `mypy .`2930## What I Do3132- Create Python 3.10+ applications (data science, backend, scripting, automation)33- Manage dependencies with uv, poetry, or pip34- Implement type hints (typing module, generics, protocols)35- Write tests with pytest (fixtures, parametrize, mocking)36- Work with pandas DataFrames (selection, groupby, merge)37- Use Python patterns (decorators, comprehensions, generators, dataclasses)38- Handle errors with logging integration39- Follow TDD workflow (Red-Green-Refactor)4041## When to Use Me4243Use this skill when you:44- Create, refactor, or debug Python 3.10+ code45- Set up projects with dependency management (uv, poetry, pip)46- Implement type hints or fix type errors47- Write pytest tests (fixtures, parametrize, mocking)48- Work with pandas DataFrames49- Use Python patterns (decorators, generators, dataclasses)50- Handle errors with logging51- Follow TDD workflows5253## Python Version Features5455| Version | Features |56|---------|----------|57| **3.10** | Pattern matching, union types (`\|`), `TypeAlias` |58| **3.11** | Exception groups (`except*`), `Self` type |59| **3.12** | Type parameters (`def func[T]`), f-string improvements |6061## Quick Reference Tables6263### Built-in Functions64| Function | Purpose |65|----------|---------|66| `map(func, iterable)` | Apply function to each item |67| `filter(func, iterable)` | Keep items where condition is True |68| `zip(*iterables)` | Combine iterables element-wise |69| `enumerate(iterable)` | Add index to iterable |7071### String Operations72| Operation | Example |73|-----------|---------|74| f-strings | `f"Hello {name}"` |75| `.join()` | `", ".join(['a', 'b'])` |76| `.split()` | `"a,b".split(",")` |7778### Collection Methods79| Type | Common Methods |80|------|----------------|81| **list** | `.append()`, `.extend()`, `.pop()`, `.sort()` |82| **dict** | `.get()`, `.keys()`, `.values()`, `.items()` |83| **set** | `.add()`, `.remove()`, `.union()` |8485## Type Hints Basics8687```python88from typing import Optional8990def greet(name: str) -> str:91 return f"Hello {name}"9293def process_items(items: list[int]) -> dict[str, int]:94 return {"count": len(items), "sum": sum(items)}9596def find_user(user_id: int) -> Optional[str]:97 return users.get(user_id)9899def parse_value(val: str | int) -> int: # Python 3.10+100 return int(val)101```102103**See [references/type-hints.md](references/type-hints.md) for Generics and Protocols.**104105## TDD Workflow (Red-Green-Refactor)1061071. **Red**: Write failing test1082. **Green**: Write minimal code to pass1093. **Refactor**: Improve while keeping tests green110111```python112# Red: Test fails (function doesn't exist)113def test_total():114 assert calculate_total([10, 20, 30]) == 60115116# Green: Make it pass117def calculate_total(items):118 return sum(items)119120# Refactor: Add types and edge cases121def calculate_total(items: list[int]) -> int:122 return sum(items) if items else 0123```124125**See [references/pytest.md](references/pytest.md) for fixtures and mocking.**126127## Error Handling with Logging128129```python130import logging131132logger = logging.getLogger(__name__)133134# Try/Except/Finally135try:136 result = risky_operation()137except ValueError as e:138 logger.error(f"Invalid value: {e}")139 raise140finally:141 cleanup_resources()142143# Custom Exceptions144class DataValidationError(Exception):145 pass146147def validate_data(data: dict) -> None:148 if "required_field" not in data:149 raise DataValidationError("required_field missing")150151# Context Manager for cleanup152from contextlib import contextmanager153154@contextmanager155def db_connection(url: str):156 conn = connect(url)157 try:158 yield conn159 finally:160 conn.close()161```162163## Examples164165### Example 1: Dataclass with Type Hints166```python167from dataclasses import dataclass168from typing import List, Optional169170@dataclass171class User:172 id: int173 name: str174 email: str175 tags: List[str] = None176 177 def __post_init__(self):178 if self.tags is None:179 self.tags = []180181# Usage182user = User(id=1, name="Alice", email="alice@example.com")183user.tags.append("admin")184```185186### Example 2: Decorator Pattern187```python188import functools189import time190import logging191192logger = logging.getLogger(__name__)193194def timing_decorator(func):195 @functools.wraps(func)196 def wrapper(*args, **kwargs):197 start = time.time()198 result = func(*args, **kwargs)199 elapsed = time.time() - start200 logger.info(f"{func.__name__} took {elapsed:.2f}s")201 return result202 return wrapper203204@timing_decorator205def slow_function():206 time.sleep(1)207 return "done"208```209210### Example 3: List Comprehension with Filtering211```python212# Filter and transform in one line213numbers = [1, 2, 3, 4, 5, 6]214even_squares = [x**2 for x in numbers if x % 2 == 0]215# Result: [4, 16, 36]216217# Dict comprehension218users = [("alice", 25), ("bob", 30)]219user_dict = {name: age for name, age in users}220# Result: {"alice": 25, "bob": 30}221```222223### Example 4: Generator for Memory Efficiency224```python225def read_large_file(file_path: str):226 with open(file_path, 'r') as f:227 for line in f:228 yield line.strip()229230for line in read_large_file("huge.txt"):231 process(line)232```233234**See [references/patterns.md](references/patterns.md) for more patterns.**235236## Common Errors237238| Error | Solution |239|-------|----------|240| `ModuleNotFoundError` | Run `uv add <package>` or `pip install <package>` |241| `TypeError` | Check types, add type hints |242| `KeyError` | Use `.get('key', default)` instead of `['key']` |243| `IndentationError` | Use 4 spaces (PEP 8) |244| `AttributeError: 'NoneType'` | Check for None: `if obj is not None:` |245246## Related Skills247248- **pytest-testing**: Fixtures, parametrize, mocking249- **pandas-data-analysis**: Advanced DataFrame operations250- **fastapi-backend**: REST APIs with FastAPI251- **django-web**: Web applications with Django252- **github-actions**: CI/CD for Python253254## References255256- [references/patterns.md](references/patterns.md) - Context managers, decorators, comprehensions, generators, dataclasses, async/await257- [references/type-hints.md](references/type-hints.md) - Advanced typing (Generics, Protocols, TypeVar, type guards)258- [references/pytest.md](references/pytest.md) - Fixtures, parametrize, mocking, assertions259- [references/pandas.md](references/pandas.md) - DataFrame operations, groupby, merge, performance260- [references/dependency-management.md](references/dependency-management.md) - uv, poetry, pip workflows and pyproject.toml