partialmethod Binds Presets Onto Class Methods
Attach preset arguments to class methods with functools.partialmethod so the descriptor protocol preserves self on instances and subclasses alike.
Code
from functools import partialmethod
class QueryClient:
def __init__(self, prefix: str) -> None:
self.prefix = prefix
def request(self, method: str, path: str, *, retries: int = 0) -> str:
return f"{method} {self.prefix}{path} (retries={retries})"
# partialmethod is a descriptor, so `self` is bound cleanly on every instance
get = partialmethod(request, "GET")
post_idempotent = partialmethod(request, "POST", retries=2)
class VersionedClient(QueryClient):
def request(self, method: str, path: str, *, retries: int = 0) -> str:
return "[v2] " + super().request(method, path, retries=retries)
base = QueryClient("/api")
v2 = VersionedClient("/api")
print(base.get("/health"))
print(base.post_idempotent("/jobs"))
print(v2.get("/users"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
GET /api/health (retries=0)
POST /api/jobs (retries=2)
GET /api/users (retries=0)Execution path — partialmethod Binds Presets Onto Class Methods
partialmethod Binds Presets Onto Class Methods is built around the classes QueryClient and VersionedClient and the functions __init__ and request.
What to watch for
- Only built-in language APIs are invoked with zero outside libraries installed.
Using it
Main routine contract starts with def request(self, method: str, path: str, *, retries: int = 0) -> str
The surface worth importing is request; the helpers around it are private to the snippet.
Key statements
def __init__(self, prefix: str) -> None:
self.prefix = prefix
def request(self, method: str, path: str, *, retries: int = 0) -> str:
return f"{method} {self.prefix}{path} (retries={retries})"
def request(self, method: str, path: str, *, retries: int = 0) -> str:
return "[v2] " + super().request(method, path, retries=retries)
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `functools`. The file defines `__init__`, `request` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.