Fixed: #2914 (RFE for UTC support in TimedRotatingFileHandler) and #2929 (wrong filen...
[python.git] / Doc / library / operator.rst
blob023bb74bcda89c6fbdf81b5740471591548f733a
1 :mod:`operator` --- Standard operators as functions
2 ===================================================
4 .. module:: operator
5    :synopsis: Functions corresponding to the standard operators.
6 .. sectionauthor:: Skip Montanaro <skip@automatrix.com>
9 .. testsetup::
10    
11    import operator
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
23 tests.
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)
30               le(a, b)
31               eq(a, b)
32               ne(a, b)
33               ge(a, b)
34               gt(a, b)
35               __lt__(a, b)
36               __le__(a, b)
37               __eq__(a, b)
38               __ne__(a, b)
39               __ge__(a, b)
40               __gt__(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.
50    .. versionadded:: 2.2
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)
57               __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.
75    .. versionadded:: 2.3
78 .. function:: is_not(a, b)
80    Return ``a is not b``.  Tests object identity.
82    .. versionadded:: 2.3
84 The mathematical and bitwise operations are the most numerous:
87 .. function:: abs(obj)
88               __abs__(obj)
90    Return the absolute value of *obj*.
93 .. function:: add(a, b)
94               __add__(a, b)
96    Return ``a + b``, for *a* and *b* numbers.
99 .. function:: and_(a, b)
100               __and__(a, b)
102    Return the bitwise and of *a* and *b*.
105 .. function:: div(a, b)
106               __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)
113               __floordiv__(a, b)
115    Return ``a // b``.
117    .. versionadded:: 2.2
120 .. function:: inv(obj)
121               invert(obj)
122               __inv__(obj)
123               __invert__(obj)
125    Return the bitwise inverse of the number *obj*.  This is equivalent to ``~obj``.
127    .. versionadded:: 2.0
128       The names :func:`invert` and :func:`__invert__`.
131 .. function:: lshift(a, b)
132               __lshift__(a, b)
134    Return *a* shifted left by *b*.
137 .. function:: mod(a, b)
138               __mod__(a, b)
140    Return ``a % b``.
143 .. function:: mul(a, b)
144               __mul__(a, b)
146    Return ``a * b``, for *a* and *b* numbers.
149 .. function:: neg(obj)
150               __neg__(obj)
152    Return *obj* negated.
155 .. function:: or_(a, b)
156               __or__(a, b)
158    Return the bitwise or of *a* and *b*.
161 .. function:: pos(obj)
162               __pos__(obj)
164    Return *obj* positive.
167 .. function:: pow(a, b)
168               __pow__(a, b)
170    Return ``a ** b``, for *a* and *b* numbers.
172    .. versionadded:: 2.3
175 .. function:: rshift(a, b)
176               __rshift__(a, b)
178    Return *a* shifted right by *b*.
181 .. function:: sub(a, b)
182               __sub__(a, b)
184    Return ``a - b``.
187 .. function:: truediv(a, b)
188               __truediv__(a, b)
190    Return ``a / b`` when ``__future__.division`` is in effect.  This is also
191    known as "true" division.
193    .. versionadded:: 2.2
196 .. function:: xor(a, b)
197               __xor__(a, b)
199    Return the bitwise exclusive or of *a* and *b*.
202 .. function:: index(a)
203               __index__(a)
205    Return *a* converted to an integer.  Equivalent to ``a.__index__()``.
207    .. versionadded:: 2.5
210 Operations which work with sequences include:
212 .. function:: concat(a, b)
213               __concat__(a, b)
215    Return ``a + b`` for *a* and *b* sequences.
218 .. function:: contains(a, b)
219               __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)
233               __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 .. function:: getitem(a, b)
245               __getitem__(a, b)
247    Return the value of *a* at index *b*.
250 .. function:: getslice(a, b, c)
251               __getslice__(a, b, c)
253    Return the slice of *a* from index *b* to index *c-1*.
256 .. function:: indexOf(a, b)
258    Return the index of the first of occurrence of *b* in *a*.
261 .. function:: repeat(a, b)
262               __repeat__(a, b)
264    Return ``a * b`` where *a* is a sequence and *b* is an integer.
267 .. function:: sequenceIncludes(...)
269    .. deprecated:: 2.0
270       Use :func:`contains` instead.
272    Alias for :func:`contains`.
275 .. function:: setitem(a, b, c)
276               __setitem__(a, b, c)
278    Set the value of *a* at index *b* to *c*.
281 .. function:: setslice(a, b, c, v)
282               __setslice__(a, b, c, v)
284    Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
286 Many operations have an "in-place" version.  The following functions provide a
287 more primitive access to in-place operators than the usual syntax does; for
288 example, the :term:`statement` ``x += y`` is equivalent to
289 ``x = operator.iadd(x, y)``.  Another way to put it is to say that
290 ``z = operator.iadd(x, y)`` is equivalent to the compound statement
291 ``z = x; z += y``.
293 .. function:: iadd(a, b)
294               __iadd__(a, b)
296    ``a = iadd(a, b)`` is equivalent to ``a += b``.
298    .. versionadded:: 2.5
301 .. function:: iand(a, b)
302               __iand__(a, b)
304    ``a = iand(a, b)`` is equivalent to ``a &= b``.
306    .. versionadded:: 2.5
309 .. function:: iconcat(a, b)
310               __iconcat__(a, b)
312    ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
314    .. versionadded:: 2.5
317 .. function:: idiv(a, b)
318               __idiv__(a, b)
320    ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
321    not in effect.
323    .. versionadded:: 2.5
326 .. function:: ifloordiv(a, b)
327               __ifloordiv__(a, b)
329    ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
331    .. versionadded:: 2.5
334 .. function:: ilshift(a, b)
335               __ilshift__(a, b)
337    ``a = ilshift(a, b)`` is equivalent to ``a <``\ ``<= b``.
339    .. versionadded:: 2.5
342 .. function:: imod(a, b)
343               __imod__(a, b)
345    ``a = imod(a, b)`` is equivalent to ``a %= b``.
347    .. versionadded:: 2.5
350 .. function:: imul(a, b)
351               __imul__(a, b)
353    ``a = imul(a, b)`` is equivalent to ``a *= b``.
355    .. versionadded:: 2.5
358 .. function:: ior(a, b)
359               __ior__(a, b)
361    ``a = ior(a, b)`` is equivalent to ``a |= b``.
363    .. versionadded:: 2.5
366 .. function:: ipow(a, b)
367               __ipow__(a, b)
369    ``a = ipow(a, b)`` is equivalent to ``a **= b``.
371    .. versionadded:: 2.5
374 .. function:: irepeat(a, b)
375               __irepeat__(a, b)
377    ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
378    *b* is an integer.
380    .. versionadded:: 2.5
383 .. function:: irshift(a, b)
384               __irshift__(a, b)
386    ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
388    .. versionadded:: 2.5
391 .. function:: isub(a, b)
392               __isub__(a, b)
394    ``a = isub(a, b)`` is equivalent to ``a -= b``.
396    .. versionadded:: 2.5
399 .. function:: itruediv(a, b)
400               __itruediv__(a, b)
402    ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
403    is in effect.
405    .. versionadded:: 2.5
408 .. function:: ixor(a, b)
409               __ixor__(a, b)
411    ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
413    .. versionadded:: 2.5
416 The :mod:`operator` module also defines a few predicates to test the type of
417 objects.
419 .. note::
421    Be careful not to misinterpret the results of these functions; only
422    :func:`isCallable` has any measure of reliability with instance objects.
423    For example:
425       >>> class C:
426       ...     pass
427       ... 
428       >>> import operator
429       >>> obj = C()
430       >>> operator.isMappingType(obj)
431       True
433 .. note::
435    Python 3 is expected to introduce abstract base classes for
436    collection types, so it should be possible to write, for example,
437    ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj,
438    collections.Sequence)``.
440 .. function:: isCallable(obj)
442    .. deprecated:: 2.0
443       Use the :func:`callable` built-in function instead.
445    Returns true if the object *obj* can be called like a function, otherwise it
446    returns false.  True is returned for functions, bound and unbound methods, class
447    objects, and instance objects which support the :meth:`__call__` method.
450 .. function:: isMappingType(obj)
452    Returns true if the object *obj* supports the mapping interface. This is true for
453    dictionaries and all instance objects defining :meth:`__getitem__`.
455    .. warning::
457       There is no reliable way to test if an instance supports the complete mapping
458       protocol since the interface itself is ill-defined.  This makes this test less
459       useful than it otherwise might be.
462 .. function:: isNumberType(obj)
464    Returns true if the object *obj* represents a number.  This is true for all
465    numeric types implemented in C.
467    .. warning::
469       There is no reliable way to test if an instance supports the complete numeric
470       interface since the interface itself is ill-defined.  This makes this test less
471       useful than it otherwise might be.
474 .. function:: isSequenceType(obj)
476    Returns true if the object *obj* supports the sequence protocol. This returns true
477    for all objects which define sequence methods in C, and for all instance objects
478    defining :meth:`__getitem__`.
480    .. warning::
482       There is no reliable way to test if an instance supports the complete sequence
483       interface since the interface itself is ill-defined.  This makes this test less
484       useful than it otherwise might be.
486 Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
487 their character equivalents.
489    >>> d = {}
490    >>> keys = range(256)
491    >>> vals = map(chr, keys)
492    >>> map(operator.setitem, [d]*len(keys), keys, vals)   # doctest: +SKIP
494 .. XXX: find a better, readable, example
496 The :mod:`operator` module also defines tools for generalized attribute and item
497 lookups.  These are useful for making fast field extractors as arguments for
498 :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
499 expect a function argument.
502 .. function:: attrgetter(attr[, args...])
504    Return a callable object that fetches *attr* from its operand. If more than one
505    attribute is requested, returns a tuple of attributes. After,
506    ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``.  After,
507    ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
508    b.date)``.
510    The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
511    the call ``f(b)`` returns ``b.date.month``.
513    .. versionadded:: 2.4
515    .. versionchanged:: 2.5
516       Added support for multiple attributes.
518    .. versionchanged:: 2.6
519       Added support for dotted attributes.
522 .. function:: itemgetter(item[, args...])
524    Return a callable object that fetches *item* from its operand using the
525    operand's :meth:`__getitem__` method.  If multiple items are specified,
526    returns a tuple of lookup values.  Equivalent to::
528         def itemgetter(*items):
529             if len(items) == 1:
530                 item = items[0]
531                 def g(obj):
532                     return obj[item]
533             else:
534                 def g(obj):
535                     return tuple(obj[item] for item in items)
536             return g
537    
538    The items can be any type accepted by the operand's :meth:`__getitem__` 
539    method.  Dictionaries accept any hashable value.  Lists, tuples, and 
540    strings accept an index or a slice:
542       >>> itemgetter(1)('ABCDEFG')
543       'B'
544       >>> itemgetter(1,3,5)('ABCDEFG')
545       ('B', 'D', 'F')
546       >>> itemgetter(slice(2,None))('ABCDEFG')
547       'CDEFG'
549    .. versionadded:: 2.4
551    .. versionchanged:: 2.5
552       Added support for multiple item extraction.
554    Example of using :func:`itemgetter` to retrieve specific fields from a
555    tuple record:
557        >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
558        >>> getcount = itemgetter(1)
559        >>> map(getcount, inventory)
560        [3, 2, 5, 1]
561        >>> sorted(inventory, key=getcount)
562        [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
565 .. function:: methodcaller(name[, args...])
567    Return a callable object that calls the method *name* on its operand.  If
568    additional arguments and/or keyword arguments are given, they will be given
569    to the method as well.  After ``f = methodcaller('name')``, the call ``f(b)``
570    returns ``b.name()``.  After ``f = methodcaller('name', 'foo', bar=1)``, the
571    call ``f(b)`` returns ``b.name('foo', bar=1)``.
573    .. versionadded:: 2.6
576 .. _operator-map:
578 Mapping Operators to Functions
579 ------------------------------
581 This table shows how abstract operations correspond to operator symbols in the
582 Python syntax and the functions in the :mod:`operator` module.
584 +-----------------------+-------------------------+---------------------------------+
585 | Operation             | Syntax                  | Function                        |
586 +=======================+=========================+=================================+
587 | Addition              | ``a + b``               | ``add(a, b)``                   |
588 +-----------------------+-------------------------+---------------------------------+
589 | Concatenation         | ``seq1 + seq2``         | ``concat(seq1, seq2)``          |
590 +-----------------------+-------------------------+---------------------------------+
591 | Containment Test      | ``obj in seq``          | ``contains(seq, obj)``          |
592 +-----------------------+-------------------------+---------------------------------+
593 | Division              | ``a / b``               | ``div(a, b)`` (without          |
594 |                       |                         | ``__future__.division``)        |
595 +-----------------------+-------------------------+---------------------------------+
596 | Division              | ``a / b``               | ``truediv(a, b)`` (with         |
597 |                       |                         | ``__future__.division``)        |
598 +-----------------------+-------------------------+---------------------------------+
599 | Division              | ``a // b``              | ``floordiv(a, b)``              |
600 +-----------------------+-------------------------+---------------------------------+
601 | Bitwise And           | ``a & b``               | ``and_(a, b)``                  |
602 +-----------------------+-------------------------+---------------------------------+
603 | Bitwise Exclusive Or  | ``a ^ b``               | ``xor(a, b)``                   |
604 +-----------------------+-------------------------+---------------------------------+
605 | Bitwise Inversion     | ``~ a``                 | ``invert(a)``                   |
606 +-----------------------+-------------------------+---------------------------------+
607 | Bitwise Or            | ``a | b``               | ``or_(a, b)``                   |
608 +-----------------------+-------------------------+---------------------------------+
609 | Exponentiation        | ``a ** b``              | ``pow(a, b)``                   |
610 +-----------------------+-------------------------+---------------------------------+
611 | Identity              | ``a is b``              | ``is_(a, b)``                   |
612 +-----------------------+-------------------------+---------------------------------+
613 | Identity              | ``a is not b``          | ``is_not(a, b)``                |
614 +-----------------------+-------------------------+---------------------------------+
615 | Indexed Assignment    | ``obj[k] = v``          | ``setitem(obj, k, v)``          |
616 +-----------------------+-------------------------+---------------------------------+
617 | Indexed Deletion      | ``del obj[k]``          | ``delitem(obj, k)``             |
618 +-----------------------+-------------------------+---------------------------------+
619 | Indexing              | ``obj[k]``              | ``getitem(obj, k)``             |
620 +-----------------------+-------------------------+---------------------------------+
621 | Left Shift            | ``a << b``              | ``lshift(a, b)``                |
622 +-----------------------+-------------------------+---------------------------------+
623 | Modulo                | ``a % b``               | ``mod(a, b)``                   |
624 +-----------------------+-------------------------+---------------------------------+
625 | Multiplication        | ``a * b``               | ``mul(a, b)``                   |
626 +-----------------------+-------------------------+---------------------------------+
627 | Negation (Arithmetic) | ``- a``                 | ``neg(a)``                      |
628 +-----------------------+-------------------------+---------------------------------+
629 | Negation (Logical)    | ``not a``               | ``not_(a)``                     |
630 +-----------------------+-------------------------+---------------------------------+
631 | Right Shift           | ``a >> b``              | ``rshift(a, b)``                |
632 +-----------------------+-------------------------+---------------------------------+
633 | Sequence Repitition   | ``seq * i``             | ``repeat(seq, i)``              |
634 +-----------------------+-------------------------+---------------------------------+
635 | Slice Assignment      | ``seq[i:j] = values``   | ``setslice(seq, i, j, values)`` |
636 +-----------------------+-------------------------+---------------------------------+
637 | Slice Deletion        | ``del seq[i:j]``        | ``delslice(seq, i, j)``         |
638 +-----------------------+-------------------------+---------------------------------+
639 | Slicing               | ``seq[i:j]``            | ``getslice(seq, i, j)``         |
640 +-----------------------+-------------------------+---------------------------------+
641 | String Formatting     | ``s % obj``             | ``mod(s, obj)``                 |
642 +-----------------------+-------------------------+---------------------------------+
643 | Subtraction           | ``a - b``               | ``sub(a, b)``                   |
644 +-----------------------+-------------------------+---------------------------------+
645 | Truth Test            | ``obj``                 | ``truth(obj)``                  |
646 +-----------------------+-------------------------+---------------------------------+
647 | Ordering              | ``a < b``               | ``lt(a, b)``                    |
648 +-----------------------+-------------------------+---------------------------------+
649 | Ordering              | ``a <= b``              | ``le(a, b)``                    |
650 +-----------------------+-------------------------+---------------------------------+
651 | Equality              | ``a == b``              | ``eq(a, b)``                    |
652 +-----------------------+-------------------------+---------------------------------+
653 | Difference            | ``a != b``              | ``ne(a, b)``                    |
654 +-----------------------+-------------------------+---------------------------------+
655 | Ordering              | ``a >= b``              | ``ge(a, b)``                    |
656 +-----------------------+-------------------------+---------------------------------+
657 | Ordering              | ``a > b``               | ``gt(a, b)``                    |
658 +-----------------------+-------------------------+---------------------------------+