This module exports a set of functions corresponding to the intrinsic
operators of Python. For example, operator.add(x, y) is equivalent
to the expression x+y. The function names are those used for special
methods; variants without leading and trailing '__' are also provided
This is the pure Python implementation of the module.
__all__ = ['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf',
'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand',
'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul',
'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift',
'is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le',
'length_hint', 'lshift', 'lt', 'matmul', 'methodcaller', 'mod',
'mul', 'ne', 'neg', 'not_', 'or_', 'pos', 'pow', 'rshift',
'setitem', 'sub', 'truediv', 'truth', 'xor']
from builtins import abs as _abs
# Comparison Operations *******************************************************#
# Logical Operations **********************************************************#
"Return True if a is true, False otherwise."
return True if a else False
# Mathematical/Bitwise Operations *********************************************#
# Sequence Operations *********************************************************#
"Same as a + b, for a and b sequences."
if not hasattr(a, '__getitem__'):
msg = "'%s' object can't be concatenated" % type(a).__name__
"Same as b in a (note reversed operands)."
"Return the number of times b occurs in a."
"Return the first index of b in a."
for i, j in enumerate(a):
raise ValueError('sequence.index(x): x not in sequence')
def length_hint(obj, default=0):
Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable.
If the object supports len(), the result will be exact. Otherwise, it may
over- or under-estimate by an arbitrary amount. The result will be an
if not isinstance(default, int):
msg = ("'%s' object cannot be interpreted as an integer" %
hint = type(obj).__length_hint__
if val is NotImplemented:
if not isinstance(val, int):
msg = ('__length_hint__ must be integer, not %s' %
msg = '__length_hint__() should return >= 0'
# Generalized Lookup Objects **************************************************#
Return a callable object that fetches the given attribute(s) from its operand.
After f = attrgetter('name'), the call f(r) returns r.name.
After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).
After h = attrgetter('name.first', 'name.last'), the call h(r) returns
(r.name.first, r.name.last).
__slots__ = ('_attrs', '_call')
def __init__(self, attr, *attrs):
if not isinstance(attr, str):
raise TypeError('attribute name must be a string')
self._attrs = (attr,) + attrs
getters = tuple(map(attrgetter, self._attrs))
return tuple(getter(obj) for getter in getters)
return '%s.%s(%s)' % (self.__class__.__module__,
self.__class__.__qualname__,
', '.join(map(repr, self._attrs)))
return self.__class__, self._attrs
Return a callable object that fetches the given item(s) from its operand.
After f = itemgetter(2), the call f(r) returns r[2].
After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
__slots__ = ('_items', '_call')
def __init__(self, item, *items):
self._items = items = (item,) + items
return tuple(obj[i] for i in items)
return '%s.%s(%s)' % (self.__class__.__module__,
', '.join(map(repr, self._items)))
return self.__class__, self._items
Return a callable object that calls the given method on its operand.
After f = methodcaller('name'), the call f(r) returns r.name().
After g = methodcaller('name', 'date', foo=1), the call g(r) returns
__slots__ = ('_name', '_args', '_kwargs')
def __init__(*args, **kwargs):
msg = "methodcaller needs at least one argument, the method name"
if not isinstance(self._name, str):
raise TypeError('method name must be a string')
return getattr(obj, self._name)(*self._args, **self._kwargs)
args = [repr(self._name)]
args.extend(map(repr, self._args))
args.extend('%s=%r' % (k, v) for k, v in self._kwargs.items())
return '%s.%s(%s)' % (self.__class__.__module__,
return self.__class__, (self._name,) + self._args
from functools import partial
return partial(self.__class__, self._name, **self._kwargs), self._args
# In-place Operations *********************************************************#
"Same as a += b, for a and b sequences."
if not hasattr(a, '__getitem__'):
msg = "'%s' object can't be concatenated" % type(a).__name__
from _operator import __doc__
# All of these "__func__ = func" assignments have to happen after importing
# from _operator to make sure they're set to the right function
__ifloordiv__ = ifloordiv