854f14d42f182e84c87475eec78b3bcb1fb177a2
[profile/ivi/python.git] / Doc / library / operator.rst
1 :mod:`operator` --- Standard operators as functions
2 ===================================================
3
4 .. module:: operator
5    :synopsis: Functions corresponding to the standard operators.
6 .. sectionauthor:: Skip Montanaro <skip@automatrix.com>
7
8
9 .. testsetup::
10
11    import operator
12    from operator import itemgetter
13
14
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.
20
21 The functions fall into categories that perform object comparisons, logical
22 operations, mathematical operations, sequence operations, and abstract type
23 tests.
24
25 The object comparison functions are useful for all objects, and are named after
26 the rich comparison operators they support:
27
28
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)
41
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.
49
50    .. versionadded:: 2.2
51
52 The logical operations are also generally applicable to all objects, and support
53 truth tests, identity tests, and boolean operations:
54
55
56 .. function:: not_(obj)
57               __not__(obj)
58
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.)
63
64
65 .. function:: truth(obj)
66
67    Return :const:`True` if *obj* is true, and :const:`False` otherwise.  This is
68    equivalent to using the :class:`bool` constructor.
69
70
71 .. function:: is_(a, b)
72
73    Return ``a is b``.  Tests object identity.
74
75    .. versionadded:: 2.3
76
77
78 .. function:: is_not(a, b)
79
80    Return ``a is not b``.  Tests object identity.
81
82    .. versionadded:: 2.3
83
84 The mathematical and bitwise operations are the most numerous:
85
86
87 .. function:: abs(obj)
88               __abs__(obj)
89
90    Return the absolute value of *obj*.
91
92
93 .. function:: add(a, b)
94               __add__(a, b)
95
96    Return ``a + b``, for *a* and *b* numbers.
97
98
99 .. function:: and_(a, b)
100               __and__(a, b)
101
102    Return the bitwise and of *a* and *b*.
103
104
105 .. function:: div(a, b)
106               __div__(a, b)
107
108    Return ``a / b`` when ``__future__.division`` is not in effect.  This is
109    also known as "classic" division.
110
111
112 .. function:: floordiv(a, b)
113               __floordiv__(a, b)
114
115    Return ``a // b``.
116
117    .. versionadded:: 2.2
118
119
120 .. function:: index(a)
121               __index__(a)
122
123    Return *a* converted to an integer.  Equivalent to ``a.__index__()``.
124
125    .. versionadded:: 2.5
126
127
128 .. function:: inv(obj)
129               invert(obj)
130               __inv__(obj)
131               __invert__(obj)
132
133    Return the bitwise inverse of the number *obj*.  This is equivalent to ``~obj``.
134
135    .. versionadded:: 2.0
136       The names :func:`invert` and :func:`__invert__`.
137
138
139 .. function:: lshift(a, b)
140               __lshift__(a, b)
141
142    Return *a* shifted left by *b*.
143
144
145 .. function:: mod(a, b)
146               __mod__(a, b)
147
148    Return ``a % b``.
149
150
151 .. function:: mul(a, b)
152               __mul__(a, b)
153
154    Return ``a * b``, for *a* and *b* numbers.
155
156
157 .. function:: neg(obj)
158               __neg__(obj)
159
160    Return *obj* negated (``-obj``).
161
162
163 .. function:: or_(a, b)
164               __or__(a, b)
165
166    Return the bitwise or of *a* and *b*.
167
168
169 .. function:: pos(obj)
170               __pos__(obj)
171
172    Return *obj* positive (``+obj``).
173
174
175 .. function:: pow(a, b)
176               __pow__(a, b)
177
178    Return ``a ** b``, for *a* and *b* numbers.
179
180    .. versionadded:: 2.3
181
182
183 .. function:: rshift(a, b)
184               __rshift__(a, b)
185
186    Return *a* shifted right by *b*.
187
188
189 .. function:: sub(a, b)
190               __sub__(a, b)
191
192    Return ``a - b``.
193
194
195 .. function:: truediv(a, b)
196               __truediv__(a, b)
197
198    Return ``a / b`` when ``__future__.division`` is in effect.  This is also
199    known as "true" division.
200
201    .. versionadded:: 2.2
202
203
204 .. function:: xor(a, b)
205               __xor__(a, b)
206
207    Return the bitwise exclusive or of *a* and *b*.
208
209
210 Operations which work with sequences (some of them with mappings too) include:
211
212 .. function:: concat(a, b)
213               __concat__(a, b)
214
215    Return ``a + b`` for *a* and *b* sequences.
216
217
218 .. function:: contains(a, b)
219               __contains__(a, b)
220
221    Return the outcome of the test ``b in a``. Note the reversed operands.
222
223    .. versionadded:: 2.0
224       The name :func:`__contains__`.
225
226
227 .. function:: countOf(a, b)
228
229    Return the number of occurrences of *b* in *a*.
230
231
232 .. function:: delitem(a, b)
233               __delitem__(a, b)
234
235    Remove the value of *a* at index *b*.
236
237
238 .. function:: delslice(a, b, c)
239               __delslice__(a, b, c)
240
241    Delete the slice of *a* from index *b* to index *c-1*.
242
243    .. deprecated:: 2.6
244       This function is removed in Python 3.x.  Use :func:`delitem` with a slice
245       index.
246
247
248 .. function:: getitem(a, b)
249               __getitem__(a, b)
250
251    Return the value of *a* at index *b*.
252
253
254 .. function:: getslice(a, b, c)
255               __getslice__(a, b, c)
256
257    Return the slice of *a* from index *b* to index *c-1*.
258
259    .. deprecated:: 2.6
260       This function is removed in Python 3.x.  Use :func:`getitem` with a slice
261       index.
262
263
264 .. function:: indexOf(a, b)
265
266    Return the index of the first of occurrence of *b* in *a*.
267
268
269 .. function:: repeat(a, b)
270               __repeat__(a, b)
271
272    .. deprecated:: 2.7
273       Use :func:`__mul__` instead.
274
275    Return ``a * b`` where *a* is a sequence and *b* is an integer.
276
277
278 .. function:: sequenceIncludes(...)
279
280    .. deprecated:: 2.0
281       Use :func:`contains` instead.
282
283    Alias for :func:`contains`.
284
285
286 .. function:: setitem(a, b, c)
287               __setitem__(a, b, c)
288
289    Set the value of *a* at index *b* to *c*.
290
291
292 .. function:: setslice(a, b, c, v)
293               __setslice__(a, b, c, v)
294
295    Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
296
297    .. deprecated:: 2.6
298       This function is removed in Python 3.x.  Use :func:`setitem` with a slice
299       index.
300
301 Example use of operator functions::
302
303     >>> # Elementwise multiplication
304     >>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
305     [0, 20, 60, 120]
306
307     >>> # Dot product
308     >>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
309     200
310
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
316 ``z = x; z += y``.
317
318 .. function:: iadd(a, b)
319               __iadd__(a, b)
320
321    ``a = iadd(a, b)`` is equivalent to ``a += b``.
322
323    .. versionadded:: 2.5
324
325
326 .. function:: iand(a, b)
327               __iand__(a, b)
328
329    ``a = iand(a, b)`` is equivalent to ``a &= b``.
330
331    .. versionadded:: 2.5
332
333
334 .. function:: iconcat(a, b)
335               __iconcat__(a, b)
336
337    ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
338
339    .. versionadded:: 2.5
340
341
342 .. function:: idiv(a, b)
343               __idiv__(a, b)
344
345    ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
346    not in effect.
347
348    .. versionadded:: 2.5
349
350
351 .. function:: ifloordiv(a, b)
352               __ifloordiv__(a, b)
353
354    ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
355
356    .. versionadded:: 2.5
357
358
359 .. function:: ilshift(a, b)
360               __ilshift__(a, b)
361
362    ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
363
364    .. versionadded:: 2.5
365
366
367 .. function:: imod(a, b)
368               __imod__(a, b)
369
370    ``a = imod(a, b)`` is equivalent to ``a %= b``.
371
372    .. versionadded:: 2.5
373
374
375 .. function:: imul(a, b)
376               __imul__(a, b)
377
378    ``a = imul(a, b)`` is equivalent to ``a *= b``.
379
380    .. versionadded:: 2.5
381
382
383 .. function:: ior(a, b)
384               __ior__(a, b)
385
386    ``a = ior(a, b)`` is equivalent to ``a |= b``.
387
388    .. versionadded:: 2.5
389
390
391 .. function:: ipow(a, b)
392               __ipow__(a, b)
393
394    ``a = ipow(a, b)`` is equivalent to ``a **= b``.
395
396    .. versionadded:: 2.5
397
398
399 .. function:: irepeat(a, b)
400               __irepeat__(a, b)
401
402    .. deprecated:: 2.7
403       Use :func:`__imul__` instead.
404
405    ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
406    *b* is an integer.
407
408    .. versionadded:: 2.5
409
410
411 .. function:: irshift(a, b)
412               __irshift__(a, b)
413
414    ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
415
416    .. versionadded:: 2.5
417
418
419 .. function:: isub(a, b)
420               __isub__(a, b)
421
422    ``a = isub(a, b)`` is equivalent to ``a -= b``.
423
424    .. versionadded:: 2.5
425
426
427 .. function:: itruediv(a, b)
428               __itruediv__(a, b)
429
430    ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
431    is in effect.
432
433    .. versionadded:: 2.5
434
435
436 .. function:: ixor(a, b)
437               __ixor__(a, b)
438
439    ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
440
441    .. versionadded:: 2.5
442
443
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).
448
449 .. function:: isCallable(obj)
450
451    .. deprecated:: 2.0
452       Use ``isinstance(x, collections.Callable)`` instead.
453
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.
457
458
459 .. function:: isMappingType(obj)
460
461    .. deprecated:: 2.7
462       Use ``isinstance(x, collections.Mapping)`` instead.
463
464    Returns true if the object *obj* supports the mapping interface. This is true for
465    dictionaries and all instance objects defining :meth:`__getitem__`.
466
467
468 .. function:: isNumberType(obj)
469
470    .. deprecated:: 2.7
471       Use ``isinstance(x, numbers.Number)`` instead.
472
473    Returns true if the object *obj* represents a number.  This is true for all
474    numeric types implemented in C.
475
476
477 .. function:: isSequenceType(obj)
478
479    .. deprecated:: 2.7
480       Use ``isinstance(x, collections.Sequence)`` instead.
481
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__`.
485
486
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.
491
492
493 .. function:: attrgetter(attr[, args...])
494
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,
499    b.date)``.  Equivalent to::
500
501       def attrgetter(*items):
502           if len(items) == 1:
503               attr = items[0]
504               def g(obj):
505                   return resolve_attr(obj, attr)
506           else:
507               def g(obj):
508                   return tuple(resolve_att(obj, attr) for attr in items)
509           return g
510
511       def resolve_attr(obj, attr):
512           for name in attr.split("."):
513               obj = getattr(obj, name)
514           return obj
515
516
517    The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
518    the call ``f(b)`` returns ``b.date.month``.
519
520    .. versionadded:: 2.4
521
522    .. versionchanged:: 2.5
523       Added support for multiple attributes.
524
525    .. versionchanged:: 2.6
526       Added support for dotted attributes.
527
528
529 .. function:: itemgetter(item[, args...])
530
531    Return a callable object that fetches *item* from its operand using the
532    operand's :meth:`__getitem__` method.  If multiple items are specified,
533    returns a tuple of lookup values.  Equivalent to::
534
535       def itemgetter(*items):
536           if len(items) == 1:
537               item = items[0]
538               def g(obj):
539                   return obj[item]
540           else:
541               def g(obj):
542                   return tuple(obj[item] for item in items)
543           return g
544
545    The items can be any type accepted by the operand's :meth:`__getitem__`
546    method.  Dictionaries accept any hashable value.  Lists, tuples, and
547    strings accept an index or a slice:
548
549       >>> itemgetter(1)('ABCDEFG')
550       'B'
551       >>> itemgetter(1,3,5)('ABCDEFG')
552       ('B', 'D', 'F')
553       >>> itemgetter(slice(2,None))('ABCDEFG')
554       'CDEFG'
555
556    .. versionadded:: 2.4
557
558    .. versionchanged:: 2.5
559       Added support for multiple item extraction.
560
561    Example of using :func:`itemgetter` to retrieve specific fields from a
562    tuple record:
563
564       >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
565       >>> getcount = itemgetter(1)
566       >>> map(getcount, inventory)
567       [3, 2, 5, 1]
568       >>> sorted(inventory, key=getcount)
569       [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
570
571
572 .. function:: methodcaller(name[, args...])
573
574    Return a callable object that calls the method *name* on its operand.  If
575    additional arguments and/or keyword arguments are given, they will be given
576    to the method as well.  After ``f = methodcaller('name')``, the call ``f(b)``
577    returns ``b.name()``.  After ``f = methodcaller('name', 'foo', bar=1)``, the
578    call ``f(b)`` returns ``b.name('foo', bar=1)``.  Equivalent to::
579
580       def methodcaller(name, *args, **kwargs):
581           def caller(obj):
582               return getattr(obj, name)(*args, **kwargs)
583           return caller
584
585    .. versionadded:: 2.6
586
587
588 .. _operator-map:
589
590 Mapping Operators to Functions
591 ------------------------------
592
593 This table shows how abstract operations correspond to operator symbols in the
594 Python syntax and the functions in the :mod:`operator` module.
595
596 +-----------------------+-------------------------+---------------------------------------+
597 | Operation             | Syntax                  | Function                              |
598 +=======================+=========================+=======================================+
599 | Addition              | ``a + b``               | ``add(a, b)``                         |
600 +-----------------------+-------------------------+---------------------------------------+
601 | Concatenation         | ``seq1 + seq2``         | ``concat(seq1, seq2)``                |
602 +-----------------------+-------------------------+---------------------------------------+
603 | Containment Test      | ``obj in seq``          | ``contains(seq, obj)``                |
604 +-----------------------+-------------------------+---------------------------------------+
605 | Division              | ``a / b``               | ``div(a, b)`` (without                |
606 |                       |                         | ``__future__.division``)              |
607 +-----------------------+-------------------------+---------------------------------------+
608 | Division              | ``a / b``               | ``truediv(a, b)`` (with               |
609 |                       |                         | ``__future__.division``)              |
610 +-----------------------+-------------------------+---------------------------------------+
611 | Division              | ``a // b``              | ``floordiv(a, b)``                    |
612 +-----------------------+-------------------------+---------------------------------------+
613 | Bitwise And           | ``a & b``               | ``and_(a, b)``                        |
614 +-----------------------+-------------------------+---------------------------------------+
615 | Bitwise Exclusive Or  | ``a ^ b``               | ``xor(a, b)``                         |
616 +-----------------------+-------------------------+---------------------------------------+
617 | Bitwise Inversion     | ``~ a``                 | ``invert(a)``                         |
618 +-----------------------+-------------------------+---------------------------------------+
619 | Bitwise Or            | ``a | b``               | ``or_(a, b)``                         |
620 +-----------------------+-------------------------+---------------------------------------+
621 | Exponentiation        | ``a ** b``              | ``pow(a, b)``                         |
622 +-----------------------+-------------------------+---------------------------------------+
623 | Identity              | ``a is b``              | ``is_(a, b)``                         |
624 +-----------------------+-------------------------+---------------------------------------+
625 | Identity              | ``a is not b``          | ``is_not(a, b)``                      |
626 +-----------------------+-------------------------+---------------------------------------+
627 | Indexed Assignment    | ``obj[k] = v``          | ``setitem(obj, k, v)``                |
628 +-----------------------+-------------------------+---------------------------------------+
629 | Indexed Deletion      | ``del obj[k]``          | ``delitem(obj, k)``                   |
630 +-----------------------+-------------------------+---------------------------------------+
631 | Indexing              | ``obj[k]``              | ``getitem(obj, k)``                   |
632 +-----------------------+-------------------------+---------------------------------------+
633 | Left Shift            | ``a << b``              | ``lshift(a, b)``                      |
634 +-----------------------+-------------------------+---------------------------------------+
635 | Modulo                | ``a % b``               | ``mod(a, b)``                         |
636 +-----------------------+-------------------------+---------------------------------------+
637 | Multiplication        | ``a * b``               | ``mul(a, b)``                         |
638 +-----------------------+-------------------------+---------------------------------------+
639 | Negation (Arithmetic) | ``- a``                 | ``neg(a)``                            |
640 +-----------------------+-------------------------+---------------------------------------+
641 | Negation (Logical)    | ``not a``               | ``not_(a)``                           |
642 +-----------------------+-------------------------+---------------------------------------+
643 | Positive              | ``+ a``                 | ``pos(a)``                            |
644 +-----------------------+-------------------------+---------------------------------------+
645 | Right Shift           | ``a >> b``              | ``rshift(a, b)``                      |
646 +-----------------------+-------------------------+---------------------------------------+
647 | Sequence Repetition   | ``seq * i``             | ``repeat(seq, i)``                    |
648 +-----------------------+-------------------------+---------------------------------------+
649 | Slice Assignment      | ``seq[i:j] = values``   | ``setitem(seq, slice(i, j), values)`` |
650 +-----------------------+-------------------------+---------------------------------------+
651 | Slice Deletion        | ``del seq[i:j]``        | ``delitem(seq, slice(i, j))``         |
652 +-----------------------+-------------------------+---------------------------------------+
653 | Slicing               | ``seq[i:j]``            | ``getitem(seq, slice(i, j))``         |
654 +-----------------------+-------------------------+---------------------------------------+
655 | String Formatting     | ``s % obj``             | ``mod(s, obj)``                       |
656 +-----------------------+-------------------------+---------------------------------------+
657 | Subtraction           | ``a - b``               | ``sub(a, b)``                         |
658 +-----------------------+-------------------------+---------------------------------------+
659 | Truth Test            | ``obj``                 | ``truth(obj)``                        |
660 +-----------------------+-------------------------+---------------------------------------+
661 | Ordering              | ``a < b``               | ``lt(a, b)``                          |
662 +-----------------------+-------------------------+---------------------------------------+
663 | Ordering              | ``a <= b``              | ``le(a, b)``                          |
664 +-----------------------+-------------------------+---------------------------------------+
665 | Equality              | ``a == b``              | ``eq(a, b)``                          |
666 +-----------------------+-------------------------+---------------------------------------+
667 | Difference            | ``a != b``              | ``ne(a, b)``                          |
668 +-----------------------+-------------------------+---------------------------------------+
669 | Ordering              | ``a >= b``              | ``ge(a, b)``                          |
670 +-----------------------+-------------------------+---------------------------------------+
671 | Ordering              | ``a > b``               | ``gt(a, b)``                          |
672 +-----------------------+-------------------------+---------------------------------------+
673