operator.methodcaller Applies One Method Per Item
methodcaller(name, *args) builds a reusable callable that invokes one method with fixed arguments on every item, turning dict.get calls into sort keys.
Code
from operator import methodcaller
# methodcaller(方法名, *参数) 生成"对每个对象调用该方法"的可复用键函数
services = [
{"name": "billing", "status": "degraded"},
{"name": "auth", "status": "ok"},
{"name": "search", "status": "ok"},
]
# dict.get 也是方法:methodcaller('get', 'status') 等价于 lambda d: d.get('status')
by_status = sorted(services, key=methodcaller("get", "status"))
print("sorted by status:", [s["name"] for s in by_status])
# 带参数调用:methodcaller('startswith', 'py') 检查每个元素
names = ["python", "javascript", "pypy", "rust"]
flagged = [n for n in names if methodcaller("startswith", "py")(n)]
print("startswith py :", flagged)
# 与 itemgetter/attrgetter 同族:itemgetter 取字段,methodcaller 调方法
words = ["Banana", "apple", "Cherry"]
print("case-insensitive:", sorted(words, key=methodcaller("lower")))
# 链式参数:methodcaller('replace', ...) 一次替换所有元素里的内容
print("replaced :", [methodcaller("replace", "a", "@")(w) for w in words])Output
Captured from a sandboxed run of this snippet in the build pipeline.
sorted by status: ['billing', 'auth', 'search']
startswith py : ['python', 'pypy']
case-insensitive: ['apple', 'Banana', 'Cherry']
replaced : ['B@n@n@', '@pple', 'Cherry']What the code does
Module-level bindings hold the data — services, by_status, names, flagged — with no function scope in between.
What to watch for
- The dependency list is empty; the language runtime covers it all.
Using it
Output lines are prefixed (sorted by status:, startswith py :, case-insensitive:), making each step’s effect easy to spot.
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 the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `operator`. Its state lives in module-level bindings: `services`, `by_status`, `names`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.