Loading...
Loading...
Use when writing new Python code, fixing bugs, refactoring, or adding tests — user says "implement", "fix", "refactor", "add tests", or is editing .py files, pyproject.toml, requirements.txt, or setup.py. Does NOT apply to reading or discussing existing code without changes.
npx skill4agent add minhhh/agent-skills python-dev| Category | Rule | How to Apply |
|---|---|---|
| Safety | Never use mutable default arguments | Use |
| Always use context managers | | |
No bare | Catch specific exceptions; bare | |
Never | Code injection; use | |
| Cross-platform, composable, readable | |
| Type Safety | Type-hint all function signatures | Enables mypy, IDE completion, and self-documenting APIs |
| Caller must handle | |
Avoid | Use | |
| Strict mode catches implicit | |
| Named fields, type-checked, no raw | |
| Async Patterns | Always | Unawaited coroutines are silent no-ops — no error, no execution |
| Sequential | |
| Never block the event loop | Use | |
| Ensures | |
| Structured concurrency; cancels siblings on first failure | |
| Testing | pytest fixtures over | Composable, reusable, cleaner setup/teardown |
| Table-driven tests — less boilerplate, clearer intent | |
| Real implementations over mocks | Mocks drift from production; use them only for external I/O | |
| Isolated temp directory per test; never hardcoded paths | |
| Code Quality | | Readable inline, evaluated eagerly, not a template injection risk |
| Communicates intent; mypy rejects reassignment | |
| Reduces per-instance memory; prevents accidental attribute creation | |
| Auto-generates |
flowchart TD
Writing_code((Writing code))
Safety_violation_{Safety violation?}
Apply_Safety_rules[Apply Safety rules]
Type_safety_violation_{Type safety violation?}
Apply_Type_Safety_rules[Apply Type Safety rules]
Async_issue_{Async correctness issue?}
Apply_Async_rules[Apply Async rules]
Apply_Code_Quality_rules[Apply Code Quality rules]
Code_complete((Code complete))
Writing_code --> Safety_violation_
Safety_violation_ -->|"yes (NEVER compromise)"| Apply_Safety_rules
Safety_violation_ -->|no| Type_safety_violation_
Apply_Safety_rules --> Code_complete
Type_safety_violation_ -->|"yes (fix before proceeding)"| Apply_Type_Safety_rules
Type_safety_violation_ -->|no| Async_issue_
Apply_Type_Safety_rules --> Code_complete
Async_issue_ -->|"yes (silent no-op or race)"| Apply_Async_rules
Async_issue_ -->|no| Apply_Code_Quality_rules
Apply_Async_rules --> Code_complete
Apply_Code_Quality_rules --> Code_complete# ❌ BAD: The list is created once and shared; tags accumulate across calls
def add_tag(tag: str, tags: list[str] = []) -> list[str]:
tags.append(tag)
return tags
add_tag("a") # ["a"]
add_tag("b") # ["a", "b"] — not ["b"]!
# ✅ GOOD: None sentinel; fresh list on every call
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
if tags is None:
tags = []
tags.append(tag)
return tagsdictset# ❌ BAD: File not closed if an exception occurs between open() and close()
f = open("data.json")
data = json.load(f)
f.close()
# ✅ GOOD: __exit__ always runs, even on exception
with open("data.json") as f:
data = json.load(f)__enter____exit__except:# ❌ BAD: Catches KeyboardInterrupt, SystemExit, GeneratorExit — blocks Ctrl-C
try:
result = risky_operation()
except:
logger.error("Something went wrong")
# ✅ GOOD: Catch only what you can handle
try:
result = risky_operation()
except (ValueError, IOError) as exc:
logger.error("Operation failed: %s", exc)
raiseexcept Exception:eval()exec()# ❌ BAD: Executes arbitrary code from the request
user_filter = request.args.get("filter")
result = eval(user_filter) # Code injection
# ✅ GOOD: Parse structured input explicitly
allowed_filters = {"active", "inactive", "pending"}
user_filter = request.args.get("filter")
if user_filter not in allowed_filters:
raise ValueError(f"Invalid filter: {user_filter!r}")ast.literal_evalpathlib.Path# ❌ BAD: String join breaks on Windows; hard to read
config_path = base_dir + "/config/" + env + ".yaml"
# ✅ GOOD: Composable, OS-aware, readable
config_path = Path(base_dir) / "config" / f"{env}.yaml"# ❌ BAD: Caller has no idea what types are expected or returned
def process_user(user, flags):
...
# ✅ GOOD: Contract is explicit; mypy can verify callers
def process_user(user: User, flags: set[str]) -> ProcessResult:
...Optional[X]X | NoneX | None# ❌ BAD: Caller doesn't know None is possible; AttributeError at runtime
def find_user(user_id: str) -> User:
return db.get(user_id) # Returns None if not found
# ✅ GOOD: None is part of the contract; mypy enforces null checks on callers
def find_user(user_id: str) -> User | None:
return db.get(user_id)AnyUnionTypeVarProtocol# ❌ BAD: Any propagates — typed code calling this function loses its types
def deserialise(data: Any) -> Any:
...
# ✅ GOOD: TypeVar preserves the relationship between input and output
T = TypeVar("T")
def deserialise(data: bytes, model: type[T]) -> T:
...mypy --strict--disallow-untyped-defs--warn-return-any--no-implicit-optional@dataclassTypedDict# ❌ BAD: No type checking; typos in key names silently produce None
user = {"user_id": "abc", "emal": "x@y.com"} # Typo — undetected
send_confirmation(user["email"]) # KeyError at runtime
# ✅ GOOD: Named fields, type-checked, IDE-autocompleted
@dataclass
class User:
user_id: str
email: str
user = User(user_id="abc", email="x@y.com")
send_confirmation(user.email) # Typo → AttributeError caught by mypyRuntimeWarningawait# ❌ BAD: save_order returns a coroutine object — it never runs
async def handle_request(order: Order) -> None:
save_order(order) # No await — silently does nothing
send_confirmation(order) # Also no await
# ✅ GOOD: Explicit await — execution is guaranteed, errors propagate
async def handle_request(order: Order) -> None:
await save_order(order)
await notify(order)asyncio.gather()# ❌ BAD: Each fetch waits for the previous to complete — O(N) latency
async def load_all(ids: list[str]) -> list[Record]:
results = []
for record_id in ids:
record = await fetch_record(record_id)
results.append(record)
return results
# ✅ GOOD: All fetches in flight simultaneously — O(1) latency
async def load_all(ids: list[str]) -> list[Record]:
return await asyncio.gather(*[fetch_record(i) for i in ids])asyncio.gather(*coros, return_exceptions=True)run_in_executor# ❌ BAD: time.sleep blocks the event loop; all other coroutines are frozen
async def poll() -> None:
time.sleep(1) # Blocks entire thread
result = do_cpu_work() # Same problem
# ✅ GOOD: Async sleep yields; executor runs blocking code in a thread pool
async def poll() -> None:
await asyncio.sleep(1)
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, do_cpu_work)asyncio.TaskGroup# ❌ BAD: Manual task tracking; exceptions may go unobserved
tasks = [asyncio.create_task(fetch(i)) for i in ids]
results = await asyncio.gather(*tasks)
# ✅ GOOD: TaskGroup cancels all siblings on first exception; cleaner lifecycle
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(i)) for i in ids]
results = [t.result() for t in tasks]unittest# ❌ BAD: setUp/tearDown are rigid; test methods share namespace
class TestUserService(unittest.TestCase):
def setUp(self):
self.service = UserService(FakeRepo())
# ✅ GOOD: Fixtures are composable and reusable across modules
@pytest.fixture
def user_service() -> UserService:
return UserService(InMemoryUserRepo())
def test_creates_user(user_service: UserService) -> None:
user = user_service.create(name="Alice", email="alice@example.com")
assert user.name == "Alice"@pytest.mark.parametrize# ❌ BAD: One test per case — repetitive, hard to extend
def test_valid_email_foo():
assert is_valid_email("foo@example.com")
def test_valid_email_bar():
assert is_valid_email("bar@example.com")
# ✅ GOOD: All cases in one declaration; failure output shows the failing input
@pytest.mark.parametrize("email,expected", [
("foo@example.com", True),
("not-an-email", False),
("", False),
("a@b.c", True),
])
def test_email_validation(email: str, expected: bool) -> None:
assert is_valid_email(email) == expected# ❌ BAD: Mock diverges from the real repository contract over time
mock_repo = MagicMock(spec=UserRepository)
mock_repo.find_by_id.return_value = User(id="1", email="a@b.com")
# ✅ GOOD: In-memory implementation honours the real interface
class InMemoryUserRepo:
def __init__(self) -> None:
self._store: dict[str, User] = {}
def save(self, user: User) -> None:
self._store[user.id] = user
def find_by_id(self, user_id: str) -> User | None:
return self._store.get(user_id)tmp_path# ❌ BAD: Leaves state on disk; breaks in parallel test runs
def test_writes_config():
write_config("/tmp/config.yaml", {"key": "value"})
assert Path("/tmp/config.yaml").exists()
# ✅ GOOD: Isolated per-test temp directory; cleaned up automatically
def test_writes_config(tmp_path: Path) -> None:
config_file = tmp_path / "config.yaml"
write_config(config_file, {"key": "value"})
assert config_file.exists()typing.Final# ❌ BAD: Any code can reassign MAX_RETRIES inadvertently
MAX_RETRIES = 3
# ✅ GOOD: Final signals to humans and tools that this value is invariant
from typing import Final
MAX_RETRIES: Final = 3__slots__# ❌ BAD: Each instance carries a full __dict__ — O(N) memory overhead
class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
# ✅ GOOD: Fixed attribute layout — less memory, faster attribute access
class Point:
__slots__ = ("x", "y")
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = ydataclasses.dataclass__init__# ❌ BAD: Manual __init__, __repr__, __eq__ — repetitive boilerplate
class Config:
def __init__(self, host: str, port: int, debug: bool = False):
self.host = host
self.port = port
self.debug = debug
# ✅ GOOD: Generated __init__, __repr__, __eq__; frozen=True makes it immutable
@dataclass(frozen=True)
class Config:
host: str
port: int
debug: bool = False.format()%# ❌ BAD: Format strings break on rename; % format is error-prone with tuples
msg = "User %s logged in from %s" % (user.name, ip_address)
msg = "User {} logged in from {}".format(user.name, ip_address)
# ✅ GOOD: Inline, readable, no positional index drift
msg = f"User {user.name} logged in from {ip_address}"| Rationalization | Problem | Impact | Fix |
|---|---|---|---|
| "I tested it manually" | Manual testing leaves no regression safety net | Next refactor breaks it silently | Write a pytest test that covers the case |
| "A global variable is convenient" | Untestable; mutated across test runs; thread-unsafe | Tests interfere; concurrent writes corrupt state | Pass dependencies explicitly or use a DI pattern |
| "The f-string expression is complex but readable" | Complex expressions in f-strings are hard to test | Formatting logic is invisible to unit tests | Extract to a variable or function first |
"Catch | Swallows unexpected bugs as mere log lines | Real bugs hidden; system in unknown state | Log AND rethrow; let unexpected exceptions propagate |