SyncAI.news, a Varaisys broadcasting
7 Python Best Practices Senior Developers Follow (That Beginners Often Miss)
ND

Nahla Davies

· 1 min read

EngineeringKDnuggets

7 Python Best Practices Senior Developers Follow (That Beginners Often Miss)

Here's a function most reviewers would wave through. It fetches some orders, calls an API, logs a line, returns a result, and every test on the happy path passes. It also builds its own HTTP client, waits on the network forever, and logs "processing failed" with no way to tell which job. And there's no way at all to exercise what happens when the service goes down. A linter would pass it without a single complaint, because none of these problems are style problems.

If naming and formatting are still the concern, the clean code crash course covers that ground well. This list starts where local tidiness stops helping. Senior Python practice, watched up close, is mostly surprise reduction. These seven habits surface the surprises before production does.

1. Passing Dependencies In Instead of Hiding Them

Code is easier to test and to replace when the caller can see which collaborator it needs. The version that hides its dependency looks innocent: somewhere inside, the function constructs its own httpx.Client() and calls the real network. Every test then either hits the internet or patches deep into module internals. The fix is to accept the collaborator, typed as small as possible:

from typing import Protocol

class OrderClient(Protocol):
    def submit(self, payload: dict) -> dict: ...

def process_order(order: dict, client: OrderClient) -> str:
    response = client.submit(order)
    return response["status"]

typing.Protocol gives you structural typing, so any object with a matching submit method satisfies the interface for static checking, no inheritance tree required. One honest caveat: Protocol is a shape for the type checker, not runtime validation, so don't expect it to reject a bad object at execution time. The payoff shows up immediately in tests, where a five-line fake that records its calls replaces the network entirely. No framework needed; when the set of collaborators grows past a handful, a registry pattern keeps the wiring explicit without one.

Original source

This story was published by KDnuggets and written by Nahla Davies. SyncAI.news shows a preview; the complete article is on the publisher's site.

Read the full story on kdnuggets.com

Similar News