attrgetter Sorts By Dotted Attribute Paths
operator.attrgetter builds attribute accessors, supports dotted paths and multiple names as tuple keys, and plugs directly into sorted, min and max.
Code
from operator import attrgetter
class Route:
def __init__(self, host, path, weight):
self.host = host
self.path = path
self.weight = weight
def __repr__(self):
return f"{self.host}{self.path}({self.weight})"
routes = [
Route("api.example.com", "/v1/orders", 3),
Route("api.example.com", "/v1/users", 1),
Route("cdn.example.com", "/assets", 2),
]
# attrgetter("host", "path") 返回取两个字段元组的访问器:一次声明多级键
key = attrgetter("host", "path")
print(sorted(routes, key=key))
# 单个 getter 可直接当 max/min 的键
heaviest = max(routes, key=attrgetter("weight"))
print("heaviest:", heaviest, "weight:", heaviest.weight)
# 点路径对嵌套对象同样有效:value.weight 一路取到底
class Config:
def __init__(self, route):
self.value = route
configs = [Config(r) for r in routes]
print([c.value.path for c in sorted(configs, key=attrgetter("value.weight"))])Output
Captured from a sandboxed run of this snippet in the build pipeline.
[api.example.com/v1/orders(3), api.example.com/v1/users(1), cdn.example.com/assets(2)]
heaviest: api.example.com/v1/orders(3) weight: 3
['/v1/users', '/assets', '/v1/orders']How the snippet works
attrgetter Sorts By Dotted Attribute Paths reduces to the classes Route and Config and the functions __init__ and __repr__.
The snippet’s external surface is attrgetter, all of it via operator.
Points of care
- Requires
operatoras a package; the snippet will not run without it.
Applying it
The primary signature is def __init__(self, host, path, weight)
Running the file prints labeled results such as heaviest: — each operation’s effect is visible in the output.
Statements that matter
def __init__(self, host, path, weight):
self.host = host
self.path = path
self.weight = weight
def __init__(self, route):
self.value = route
def __repr__(self):
return f"{self.host}{self.path}({self.weight})"
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `operator`. The file defines `__init__`, `__repr__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.