Python Glossary Русский

all Python 3operatorfunction

operator.methodcaller

calls and access

A factory returning a callable that calls a fixed method on its argument.

Syntax

f = operator.methodcaller('method', *args)

Arguments are fixed when the caller is created: methodcaller('split', ',') will always split on commas. It helps when a method must be applied to every item: map(methodcaller('strip'), lines). For a method without arguments passing the class method is simpler — map(str.strip, lines) — but that works for a single type, while methodcaller works for any object with such a method.

Examples

import operator
g = operator.methodcaller('upper')
print(g('abc'))   # → ABC
print(operator.methodcaller('upper')('abc') == 'abc'.upper())   # → True
print(operator.methodcaller('replace', 'a', 'z')('banana'))   # → bznznz
print(list(map(operator.methodcaller('strip'), [' a ', ' b'])))   # → ['a', 'b']
print(operator.methodcaller('upper')(5))   # → AttributeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy