1 :mod:`operator` --- Standard operators as functions
2 ===================================================
5 :synopsis: Functions corresponding to the standard operators.
6 .. sectionauthor:: Skip Montanaro <skip@automatrix.com>
12 from operator import itemgetter
15 The :mod:`operator` module exports a set of functions implemented in C
16 corresponding to the intrinsic operators of Python. For example,
17 ``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function
18 names are those used for special class methods; variants without leading and
19 trailing ``__`` are also provided for convenience.
21 The functions fall into categories that perform object comparisons, logical
22 operations, mathematical operations, sequence operations, and abstract type
25 The object comparison functions are useful for all objects, and are named after
26 the rich comparison operators they support:
29 .. function:: lt(a, b)
42 Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
43 equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
44 b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
45 ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
46 >= b``. Note that unlike the built-in :func:`cmp`, these functions can
47 return any value, which may or may not be interpretable as a Boolean value.
48 See :ref:`comparisons` for more information about rich comparisons.
52 The logical operations are also generally applicable to all objects, and support
53 truth tests, identity tests, and boolean operations:
56 .. function:: not_(obj)
59 Return the outcome of :keyword:`not` *obj*. (Note that there is no
60 :meth:`__not__` method for object instances; only the interpreter core defines
61 this operation. The result is affected by the :meth:`__nonzero__` and
62 :meth:`__len__` methods.)
65 .. function:: truth(obj)
67 Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
68 equivalent to using the :class:`bool` constructor.
71 .. function:: is_(a, b)
73 Return ``a is b``. Tests object identity.
78 .. function:: is_not(a, b)
80 Return ``a is not b``. Tests object identity.
84 The mathematical and bitwise operations are the most numerous:
87 .. function:: abs(obj)
90 Return the absolute value of *obj*.
93 .. function:: add(a, b)
96 Return ``a + b``, for *a* and *b* numbers.
99 .. function:: and_(a, b)
102 Return the bitwise and of *a* and *b*.
105 .. function:: div(a, b)
108 Return ``a / b`` when ``__future__.division`` is not in effect. This is
109 also known as "classic" division.
112 .. function:: floordiv(a, b)
117 .. versionadded:: 2.2
120 .. function:: index(a)
123 Return *a* converted to an integer. Equivalent to ``a.__index__()``.
125 .. versionadded:: 2.5
128 .. function:: inv(obj)
133 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
135 .. versionadded:: 2.0
136 The names :func:`invert` and :func:`__invert__`.
139 .. function:: lshift(a, b)
142 Return *a* shifted left by *b*.
145 .. function:: mod(a, b)
151 .. function:: mul(a, b)
154 Return ``a * b``, for *a* and *b* numbers.
157 .. function:: neg(obj)
160 Return *obj* negated (``-obj``).
163 .. function:: or_(a, b)
166 Return the bitwise or of *a* and *b*.
169 .. function:: pos(obj)
172 Return *obj* positive (``+obj``).
175 .. function:: pow(a, b)
178 Return ``a ** b``, for *a* and *b* numbers.
180 .. versionadded:: 2.3
183 .. function:: rshift(a, b)
186 Return *a* shifted right by *b*.
189 .. function:: sub(a, b)
195 .. function:: truediv(a, b)
198 Return ``a / b`` when ``__future__.division`` is in effect. This is also
199 known as "true" division.
201 .. versionadded:: 2.2
204 .. function:: xor(a, b)
207 Return the bitwise exclusive or of *a* and *b*.
210 Operations which work with sequences (some of them with mappings too) include:
212 .. function:: concat(a, b)
215 Return ``a + b`` for *a* and *b* sequences.
218 .. function:: contains(a, b)
221 Return the outcome of the test ``b in a``. Note the reversed operands.
223 .. versionadded:: 2.0
224 The name :func:`__contains__`.
227 .. function:: countOf(a, b)
229 Return the number of occurrences of *b* in *a*.
232 .. function:: delitem(a, b)
235 Remove the value of *a* at index *b*.
238 .. function:: delslice(a, b, c)
239 __delslice__(a, b, c)
241 Delete the slice of *a* from index *b* to index *c-1*.
244 This function is removed in Python 3.x. Use :func:`delitem` with a slice
248 .. function:: getitem(a, b)
251 Return the value of *a* at index *b*.
254 .. function:: getslice(a, b, c)
255 __getslice__(a, b, c)
257 Return the slice of *a* from index *b* to index *c-1*.
260 This function is removed in Python 3.x. Use :func:`getitem` with a slice
264 .. function:: indexOf(a, b)
266 Return the index of the first of occurrence of *b* in *a*.
269 .. function:: repeat(a, b)
273 Use :func:`__mul__` instead.
275 Return ``a * b`` where *a* is a sequence and *b* is an integer.
278 .. function:: sequenceIncludes(...)
281 Use :func:`contains` instead.
283 Alias for :func:`contains`.
286 .. function:: setitem(a, b, c)
289 Set the value of *a* at index *b* to *c*.
292 .. function:: setslice(a, b, c, v)
293 __setslice__(a, b, c, v)
295 Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
298 This function is removed in Python 3.x. Use :func:`setitem` with a slice
301 Example use of operator functions::
303 >>> # Elementwise multiplication
304 >>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
308 >>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
311 Many operations have an "in-place" version. The following functions provide a
312 more primitive access to in-place operators than the usual syntax does; for
313 example, the :term:`statement` ``x += y`` is equivalent to
314 ``x = operator.iadd(x, y)``. Another way to put it is to say that
315 ``z = operator.iadd(x, y)`` is equivalent to the compound statement
318 .. function:: iadd(a, b)
321 ``a = iadd(a, b)`` is equivalent to ``a += b``.
323 .. versionadded:: 2.5
326 .. function:: iand(a, b)
329 ``a = iand(a, b)`` is equivalent to ``a &= b``.
331 .. versionadded:: 2.5
334 .. function:: iconcat(a, b)
337 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
339 .. versionadded:: 2.5
342 .. function:: idiv(a, b)
345 ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
348 .. versionadded:: 2.5
351 .. function:: ifloordiv(a, b)
354 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
356 .. versionadded:: 2.5
359 .. function:: ilshift(a, b)
362 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
364 .. versionadded:: 2.5
367 .. function:: imod(a, b)
370 ``a = imod(a, b)`` is equivalent to ``a %= b``.
372 .. versionadded:: 2.5
375 .. function:: imul(a, b)
378 ``a = imul(a, b)`` is equivalent to ``a *= b``.
380 .. versionadded:: 2.5
383 .. function:: ior(a, b)
386 ``a = ior(a, b)`` is equivalent to ``a |= b``.
388 .. versionadded:: 2.5
391 .. function:: ipow(a, b)
394 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
396 .. versionadded:: 2.5
399 .. function:: irepeat(a, b)
403 Use :func:`__imul__` instead.
405 ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
408 .. versionadded:: 2.5
411 .. function:: irshift(a, b)
414 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
416 .. versionadded:: 2.5
419 .. function:: isub(a, b)
422 ``a = isub(a, b)`` is equivalent to ``a -= b``.
424 .. versionadded:: 2.5
427 .. function:: itruediv(a, b)
430 ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
433 .. versionadded:: 2.5
436 .. function:: ixor(a, b)
439 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
441 .. versionadded:: 2.5
444 The :mod:`operator` module also defines a few predicates to test the type of
445 objects; however, these are not all reliable. It is preferable to test
446 abstract base classes instead (see :mod:`collections` and
447 :mod:`numbers` for details).
449 .. function:: isCallable(obj)
452 Use ``isinstance(x, collections.Callable)`` instead.
454 Returns true if the object *obj* can be called like a function, otherwise it
455 returns false. True is returned for functions, bound and unbound methods, class
456 objects, and instance objects which support the :meth:`__call__` method.
459 .. function:: isMappingType(obj)
462 Use ``isinstance(x, collections.Mapping)`` instead.
464 Returns true if the object *obj* supports the mapping interface. This is true for
465 dictionaries and all instance objects defining :meth:`__getitem__`.
468 .. function:: isNumberType(obj)
471 Use ``isinstance(x, numbers.Number)`` instead.
473 Returns true if the object *obj* represents a number. This is true for all
474 numeric types implemented in C.
477 .. function:: isSequenceType(obj)
480 Use ``isinstance(x, collections.Sequence)`` instead.
482 Returns true if the object *obj* supports the sequence protocol. This returns true
483 for all objects which define sequence methods in C, and for all instance objects
484 defining :meth:`__getitem__`.
487 The :mod:`operator` module also defines tools for generalized attribute and item
488 lookups. These are useful for making fast field extractors as arguments for
489 :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
490 expect a function argument.
493 .. function:: attrgetter(attr[, args...])
495 Return a callable object that fetches *attr* from its operand. If more than one
496 attribute is requested, returns a tuple of attributes. After,
497 ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
498 ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
501 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
502 the call ``f(b)`` returns ``b.date.month``.
504 .. versionadded:: 2.4
506 .. versionchanged:: 2.5
507 Added support for multiple attributes.
509 .. versionchanged:: 2.6
510 Added support for dotted attributes.
513 .. function:: itemgetter(item[, args...])
515 Return a callable object that fetches *item* from its operand using the
516 operand's :meth:`__getitem__` method. If multiple items are specified,
517 returns a tuple of lookup values. Equivalent to::
519 def itemgetter(*items):
526 return tuple(obj[item] for item in items)
529 The items can be any type accepted by the operand's :meth:`__getitem__`
530 method. Dictionaries accept any hashable value. Lists, tuples, and
531 strings accept an index or a slice:
533 >>> itemgetter(1)('ABCDEFG')
535 >>> itemgetter(1,3,5)('ABCDEFG')
537 >>> itemgetter(slice(2,None))('ABCDEFG')
540 .. versionadded:: 2.4
542 .. versionchanged:: 2.5
543 Added support for multiple item extraction.
545 Example of using :func:`itemgetter` to retrieve specific fields from a
548 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
549 >>> getcount = itemgetter(1)
550 >>> map(getcount, inventory)
552 >>> sorted(inventory, key=getcount)
553 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
556 .. function:: methodcaller(name[, args...])
558 Return a callable object that calls the method *name* on its operand. If
559 additional arguments and/or keyword arguments are given, they will be given
560 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
561 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
562 call ``f(b)`` returns ``b.name('foo', bar=1)``.
564 .. versionadded:: 2.6
569 Mapping Operators to Functions
570 ------------------------------
572 This table shows how abstract operations correspond to operator symbols in the
573 Python syntax and the functions in the :mod:`operator` module.
575 +-----------------------+-------------------------+---------------------------------------+
576 | Operation | Syntax | Function |
577 +=======================+=========================+=======================================+
578 | Addition | ``a + b`` | ``add(a, b)`` |
579 +-----------------------+-------------------------+---------------------------------------+
580 | Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
581 +-----------------------+-------------------------+---------------------------------------+
582 | Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
583 +-----------------------+-------------------------+---------------------------------------+
584 | Division | ``a / b`` | ``div(a, b)`` (without |
585 | | | ``__future__.division``) |
586 +-----------------------+-------------------------+---------------------------------------+
587 | Division | ``a / b`` | ``truediv(a, b)`` (with |
588 | | | ``__future__.division``) |
589 +-----------------------+-------------------------+---------------------------------------+
590 | Division | ``a // b`` | ``floordiv(a, b)`` |
591 +-----------------------+-------------------------+---------------------------------------+
592 | Bitwise And | ``a & b`` | ``and_(a, b)`` |
593 +-----------------------+-------------------------+---------------------------------------+
594 | Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
595 +-----------------------+-------------------------+---------------------------------------+
596 | Bitwise Inversion | ``~ a`` | ``invert(a)`` |
597 +-----------------------+-------------------------+---------------------------------------+
598 | Bitwise Or | ``a | b`` | ``or_(a, b)`` |
599 +-----------------------+-------------------------+---------------------------------------+
600 | Exponentiation | ``a ** b`` | ``pow(a, b)`` |
601 +-----------------------+-------------------------+---------------------------------------+
602 | Identity | ``a is b`` | ``is_(a, b)`` |
603 +-----------------------+-------------------------+---------------------------------------+
604 | Identity | ``a is not b`` | ``is_not(a, b)`` |
605 +-----------------------+-------------------------+---------------------------------------+
606 | Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
607 +-----------------------+-------------------------+---------------------------------------+
608 | Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
609 +-----------------------+-------------------------+---------------------------------------+
610 | Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
611 +-----------------------+-------------------------+---------------------------------------+
612 | Left Shift | ``a << b`` | ``lshift(a, b)`` |
613 +-----------------------+-------------------------+---------------------------------------+
614 | Modulo | ``a % b`` | ``mod(a, b)`` |
615 +-----------------------+-------------------------+---------------------------------------+
616 | Multiplication | ``a * b`` | ``mul(a, b)`` |
617 +-----------------------+-------------------------+---------------------------------------+
618 | Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
619 +-----------------------+-------------------------+---------------------------------------+
620 | Negation (Logical) | ``not a`` | ``not_(a)`` |
621 +-----------------------+-------------------------+---------------------------------------+
622 | Positive | ``+ a`` | ``pos(a)`` |
623 +-----------------------+-------------------------+---------------------------------------+
624 | Right Shift | ``a >> b`` | ``rshift(a, b)`` |
625 +-----------------------+-------------------------+---------------------------------------+
626 | Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
627 +-----------------------+-------------------------+---------------------------------------+
628 | Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
629 +-----------------------+-------------------------+---------------------------------------+
630 | Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
631 +-----------------------+-------------------------+---------------------------------------+
632 | Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
633 +-----------------------+-------------------------+---------------------------------------+
634 | String Formatting | ``s % obj`` | ``mod(s, obj)`` |
635 +-----------------------+-------------------------+---------------------------------------+
636 | Subtraction | ``a - b`` | ``sub(a, b)`` |
637 +-----------------------+-------------------------+---------------------------------------+
638 | Truth Test | ``obj`` | ``truth(obj)`` |
639 +-----------------------+-------------------------+---------------------------------------+
640 | Ordering | ``a < b`` | ``lt(a, b)`` |
641 +-----------------------+-------------------------+---------------------------------------+
642 | Ordering | ``a <= b`` | ``le(a, b)`` |
643 +-----------------------+-------------------------+---------------------------------------+
644 | Equality | ``a == b`` | ``eq(a, b)`` |
645 +-----------------------+-------------------------+---------------------------------------+
646 | Difference | ``a != b`` | ``ne(a, b)`` |
647 +-----------------------+-------------------------+---------------------------------------+
648 | Ordering | ``a >= b`` | ``ge(a, b)`` |
649 +-----------------------+-------------------------+---------------------------------------+
650 | Ordering | ``a > b`` | ``gt(a, b)`` |
651 +-----------------------+-------------------------+---------------------------------------+