• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`operator` --- Standard operators as functions
2===================================================
3
4.. module:: operator
5   :synopsis: Functions corresponding to the standard operators.
6
7.. sectionauthor:: Skip Montanaro <skip@automatrix.com>
8
9**Source code:** :source:`Lib/operator.py`
10
11.. testsetup::
12
13   import operator
14   from operator import itemgetter, iadd
15
16--------------
17
18The :mod:`operator` module exports a set of efficient functions corresponding to
19the intrinsic operators of Python.  For example, ``operator.add(x, y)`` is
20equivalent to the expression ``x+y``.  The function names are those used for
21special class methods; variants without leading and trailing ``__`` are also
22provided for convenience.
23
24The functions fall into categories that perform object comparisons, logical
25operations, mathematical operations and sequence operations.
26
27The object comparison functions are useful for all objects, and are named after
28the rich comparison operators they support:
29
30
31.. function:: lt(a, b)
32              le(a, b)
33              eq(a, b)
34              ne(a, b)
35              ge(a, b)
36              gt(a, b)
37              __lt__(a, b)
38              __le__(a, b)
39              __eq__(a, b)
40              __ne__(a, b)
41              __ge__(a, b)
42              __gt__(a, b)
43
44   Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
45   equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
46   b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
47   ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
48   >= b``.  Note that these functions can return any value, which may
49   or may not be interpretable as a Boolean value.  See
50   :ref:`comparisons` for more information about rich comparisons.
51
52
53The logical operations are also generally applicable to all objects, and support
54truth tests, identity tests, and boolean operations:
55
56
57.. function:: not_(obj)
58              __not__(obj)
59
60   Return the outcome of :keyword:`not` *obj*.  (Note that there is no
61   :meth:`__not__` method for object instances; only the interpreter core defines
62   this operation.  The result is affected by the :meth:`__bool__` and
63   :meth:`__len__` methods.)
64
65
66.. function:: truth(obj)
67
68   Return :const:`True` if *obj* is true, and :const:`False` otherwise.  This is
69   equivalent to using the :class:`bool` constructor.
70
71
72.. function:: is_(a, b)
73
74   Return ``a is b``.  Tests object identity.
75
76
77.. function:: is_not(a, b)
78
79   Return ``a is not b``.  Tests object identity.
80
81
82The mathematical and bitwise operations are the most numerous:
83
84
85.. function:: abs(obj)
86              __abs__(obj)
87
88   Return the absolute value of *obj*.
89
90
91.. function:: add(a, b)
92              __add__(a, b)
93
94   Return ``a + b``, for *a* and *b* numbers.
95
96
97.. function:: and_(a, b)
98              __and__(a, b)
99
100   Return the bitwise and of *a* and *b*.
101
102
103.. function:: floordiv(a, b)
104              __floordiv__(a, b)
105
106   Return ``a // b``.
107
108
109.. function:: index(a)
110              __index__(a)
111
112   Return *a* converted to an integer.  Equivalent to ``a.__index__()``.
113
114
115.. function:: inv(obj)
116              invert(obj)
117              __inv__(obj)
118              __invert__(obj)
119
120   Return the bitwise inverse of the number *obj*.  This is equivalent to ``~obj``.
121
122
123.. function:: lshift(a, b)
124              __lshift__(a, b)
125
126   Return *a* shifted left by *b*.
127
128
129.. function:: mod(a, b)
130              __mod__(a, b)
131
132   Return ``a % b``.
133
134
135.. function:: mul(a, b)
136              __mul__(a, b)
137
138   Return ``a * b``, for *a* and *b* numbers.
139
140
141.. function:: matmul(a, b)
142              __matmul__(a, b)
143
144   Return ``a @ b``.
145
146   .. versionadded:: 3.5
147
148
149.. function:: neg(obj)
150              __neg__(obj)
151
152   Return *obj* negated (``-obj``).
153
154
155.. function:: or_(a, b)
156              __or__(a, b)
157
158   Return the bitwise or of *a* and *b*.
159
160
161.. function:: pos(obj)
162              __pos__(obj)
163
164   Return *obj* positive (``+obj``).
165
166
167.. function:: pow(a, b)
168              __pow__(a, b)
169
170   Return ``a ** b``, for *a* and *b* numbers.
171
172
173.. function:: rshift(a, b)
174              __rshift__(a, b)
175
176   Return *a* shifted right by *b*.
177
178
179.. function:: sub(a, b)
180              __sub__(a, b)
181
182   Return ``a - b``.
183
184
185.. function:: truediv(a, b)
186              __truediv__(a, b)
187
188   Return ``a / b`` where 2/3 is .66 rather than 0.  This is also known as
189   "true" division.
190
191
192.. function:: xor(a, b)
193              __xor__(a, b)
194
195   Return the bitwise exclusive or of *a* and *b*.
196
197
198Operations which work with sequences (some of them with mappings too) include:
199
200.. function:: concat(a, b)
201              __concat__(a, b)
202
203   Return ``a + b`` for *a* and *b* sequences.
204
205
206.. function:: contains(a, b)
207              __contains__(a, b)
208
209   Return the outcome of the test ``b in a``. Note the reversed operands.
210
211
212.. function:: countOf(a, b)
213
214   Return the number of occurrences of *b* in *a*.
215
216
217.. function:: delitem(a, b)
218              __delitem__(a, b)
219
220   Remove the value of *a* at index *b*.
221
222
223.. function:: getitem(a, b)
224              __getitem__(a, b)
225
226   Return the value of *a* at index *b*.
227
228
229.. function:: indexOf(a, b)
230
231   Return the index of the first of occurrence of *b* in *a*.
232
233
234.. function:: setitem(a, b, c)
235              __setitem__(a, b, c)
236
237   Set the value of *a* at index *b* to *c*.
238
239
240.. function:: length_hint(obj, default=0)
241
242   Return an estimated length for the object *o*. First try to return its
243   actual length, then an estimate using :meth:`object.__length_hint__`, and
244   finally return the default value.
245
246   .. versionadded:: 3.4
247
248The :mod:`operator` module also defines tools for generalized attribute and item
249lookups.  These are useful for making fast field extractors as arguments for
250:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
251expect a function argument.
252
253
254.. function:: attrgetter(attr)
255              attrgetter(*attrs)
256
257   Return a callable object that fetches *attr* from its operand.
258   If more than one attribute is requested, returns a tuple of attributes.
259   The attribute names can also contain dots. For example:
260
261   * After ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``.
262
263   * After ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns
264     ``(b.name, b.date)``.
265
266   * After ``f = attrgetter('name.first', 'name.last')``, the call ``f(b)``
267     returns ``(b.name.first, b.name.last)``.
268
269   Equivalent to::
270
271      def attrgetter(*items):
272          if any(not isinstance(item, str) for item in items):
273              raise TypeError('attribute name must be a string')
274          if len(items) == 1:
275              attr = items[0]
276              def g(obj):
277                  return resolve_attr(obj, attr)
278          else:
279              def g(obj):
280                  return tuple(resolve_attr(obj, attr) for attr in items)
281          return g
282
283      def resolve_attr(obj, attr):
284          for name in attr.split("."):
285              obj = getattr(obj, name)
286          return obj
287
288
289.. function:: itemgetter(item)
290              itemgetter(*items)
291
292   Return a callable object that fetches *item* from its operand using the
293   operand's :meth:`__getitem__` method.  If multiple items are specified,
294   returns a tuple of lookup values.  For example:
295
296   * After ``f = itemgetter(2)``, the call ``f(r)`` returns ``r[2]``.
297
298   * After ``g = itemgetter(2, 5, 3)``, the call ``g(r)`` returns
299     ``(r[2], r[5], r[3])``.
300
301   Equivalent to::
302
303      def itemgetter(*items):
304          if len(items) == 1:
305              item = items[0]
306              def g(obj):
307                  return obj[item]
308          else:
309              def g(obj):
310                  return tuple(obj[item] for item in items)
311          return g
312
313   The items can be any type accepted by the operand's :meth:`__getitem__`
314   method.  Dictionaries accept any hashable value.  Lists, tuples, and
315   strings accept an index or a slice:
316
317      >>> itemgetter(1)('ABCDEFG')
318      'B'
319      >>> itemgetter(1,3,5)('ABCDEFG')
320      ('B', 'D', 'F')
321      >>> itemgetter(slice(2,None))('ABCDEFG')
322      'CDEFG'
323
324
325   Example of using :func:`itemgetter` to retrieve specific fields from a
326   tuple record:
327
328      >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
329      >>> getcount = itemgetter(1)
330      >>> list(map(getcount, inventory))
331      [3, 2, 5, 1]
332      >>> sorted(inventory, key=getcount)
333      [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
334
335
336.. function:: methodcaller(name[, args...])
337
338   Return a callable object that calls the method *name* on its operand.  If
339   additional arguments and/or keyword arguments are given, they will be given
340   to the method as well.  For example:
341
342   * After ``f = methodcaller('name')``, the call ``f(b)`` returns ``b.name()``.
343
344   * After ``f = methodcaller('name', 'foo', bar=1)``, the call ``f(b)``
345     returns ``b.name('foo', bar=1)``.
346
347   Equivalent to::
348
349      def methodcaller(name, *args, **kwargs):
350          def caller(obj):
351              return getattr(obj, name)(*args, **kwargs)
352          return caller
353
354
355.. _operator-map:
356
357Mapping Operators to Functions
358------------------------------
359
360This table shows how abstract operations correspond to operator symbols in the
361Python syntax and the functions in the :mod:`operator` module.
362
363+-----------------------+-------------------------+---------------------------------------+
364| Operation             | Syntax                  | Function                              |
365+=======================+=========================+=======================================+
366| Addition              | ``a + b``               | ``add(a, b)``                         |
367+-----------------------+-------------------------+---------------------------------------+
368| Concatenation         | ``seq1 + seq2``         | ``concat(seq1, seq2)``                |
369+-----------------------+-------------------------+---------------------------------------+
370| Containment Test      | ``obj in seq``          | ``contains(seq, obj)``                |
371+-----------------------+-------------------------+---------------------------------------+
372| Division              | ``a / b``               | ``truediv(a, b)``                     |
373+-----------------------+-------------------------+---------------------------------------+
374| Division              | ``a // b``              | ``floordiv(a, b)``                    |
375+-----------------------+-------------------------+---------------------------------------+
376| Bitwise And           | ``a & b``               | ``and_(a, b)``                        |
377+-----------------------+-------------------------+---------------------------------------+
378| Bitwise Exclusive Or  | ``a ^ b``               | ``xor(a, b)``                         |
379+-----------------------+-------------------------+---------------------------------------+
380| Bitwise Inversion     | ``~ a``                 | ``invert(a)``                         |
381+-----------------------+-------------------------+---------------------------------------+
382| Bitwise Or            | ``a | b``               | ``or_(a, b)``                         |
383+-----------------------+-------------------------+---------------------------------------+
384| Exponentiation        | ``a ** b``              | ``pow(a, b)``                         |
385+-----------------------+-------------------------+---------------------------------------+
386| Identity              | ``a is b``              | ``is_(a, b)``                         |
387+-----------------------+-------------------------+---------------------------------------+
388| Identity              | ``a is not b``          | ``is_not(a, b)``                      |
389+-----------------------+-------------------------+---------------------------------------+
390| Indexed Assignment    | ``obj[k] = v``          | ``setitem(obj, k, v)``                |
391+-----------------------+-------------------------+---------------------------------------+
392| Indexed Deletion      | ``del obj[k]``          | ``delitem(obj, k)``                   |
393+-----------------------+-------------------------+---------------------------------------+
394| Indexing              | ``obj[k]``              | ``getitem(obj, k)``                   |
395+-----------------------+-------------------------+---------------------------------------+
396| Left Shift            | ``a << b``              | ``lshift(a, b)``                      |
397+-----------------------+-------------------------+---------------------------------------+
398| Modulo                | ``a % b``               | ``mod(a, b)``                         |
399+-----------------------+-------------------------+---------------------------------------+
400| Multiplication        | ``a * b``               | ``mul(a, b)``                         |
401+-----------------------+-------------------------+---------------------------------------+
402| Matrix Multiplication | ``a @ b``               | ``matmul(a, b)``                      |
403+-----------------------+-------------------------+---------------------------------------+
404| Negation (Arithmetic) | ``- a``                 | ``neg(a)``                            |
405+-----------------------+-------------------------+---------------------------------------+
406| Negation (Logical)    | ``not a``               | ``not_(a)``                           |
407+-----------------------+-------------------------+---------------------------------------+
408| Positive              | ``+ a``                 | ``pos(a)``                            |
409+-----------------------+-------------------------+---------------------------------------+
410| Right Shift           | ``a >> b``              | ``rshift(a, b)``                      |
411+-----------------------+-------------------------+---------------------------------------+
412| Slice Assignment      | ``seq[i:j] = values``   | ``setitem(seq, slice(i, j), values)`` |
413+-----------------------+-------------------------+---------------------------------------+
414| Slice Deletion        | ``del seq[i:j]``        | ``delitem(seq, slice(i, j))``         |
415+-----------------------+-------------------------+---------------------------------------+
416| Slicing               | ``seq[i:j]``            | ``getitem(seq, slice(i, j))``         |
417+-----------------------+-------------------------+---------------------------------------+
418| String Formatting     | ``s % obj``             | ``mod(s, obj)``                       |
419+-----------------------+-------------------------+---------------------------------------+
420| Subtraction           | ``a - b``               | ``sub(a, b)``                         |
421+-----------------------+-------------------------+---------------------------------------+
422| Truth Test            | ``obj``                 | ``truth(obj)``                        |
423+-----------------------+-------------------------+---------------------------------------+
424| Ordering              | ``a < b``               | ``lt(a, b)``                          |
425+-----------------------+-------------------------+---------------------------------------+
426| Ordering              | ``a <= b``              | ``le(a, b)``                          |
427+-----------------------+-------------------------+---------------------------------------+
428| Equality              | ``a == b``              | ``eq(a, b)``                          |
429+-----------------------+-------------------------+---------------------------------------+
430| Difference            | ``a != b``              | ``ne(a, b)``                          |
431+-----------------------+-------------------------+---------------------------------------+
432| Ordering              | ``a >= b``              | ``ge(a, b)``                          |
433+-----------------------+-------------------------+---------------------------------------+
434| Ordering              | ``a > b``               | ``gt(a, b)``                          |
435+-----------------------+-------------------------+---------------------------------------+
436
437Inplace Operators
438-----------------
439
440Many operations have an "in-place" version.  Listed below are functions
441providing a more primitive access to in-place operators than the usual syntax
442does; for example, the :term:`statement` ``x += y`` is equivalent to
443``x = operator.iadd(x, y)``.  Another way to put it is to say that
444``z = operator.iadd(x, y)`` is equivalent to the compound statement
445``z = x; z += y``.
446
447In those examples, note that when an in-place method is called, the computation
448and assignment are performed in two separate steps.  The in-place functions
449listed below only do the first step, calling the in-place method.  The second
450step, assignment, is not handled.
451
452For immutable targets such as strings, numbers, and tuples, the updated
453value is computed, but not assigned back to the input variable:
454
455>>> a = 'hello'
456>>> iadd(a, ' world')
457'hello world'
458>>> a
459'hello'
460
461For mutable targets such as lists and dictionaries, the inplace method
462will perform the update, so no subsequent assignment is necessary:
463
464>>> s = ['h', 'e', 'l', 'l', 'o']
465>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
466['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
467>>> s
468['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
469
470.. function:: iadd(a, b)
471              __iadd__(a, b)
472
473   ``a = iadd(a, b)`` is equivalent to ``a += b``.
474
475
476.. function:: iand(a, b)
477              __iand__(a, b)
478
479   ``a = iand(a, b)`` is equivalent to ``a &= b``.
480
481
482.. function:: iconcat(a, b)
483              __iconcat__(a, b)
484
485   ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
486
487
488.. function:: ifloordiv(a, b)
489              __ifloordiv__(a, b)
490
491   ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
492
493
494.. function:: ilshift(a, b)
495              __ilshift__(a, b)
496
497   ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
498
499
500.. function:: imod(a, b)
501              __imod__(a, b)
502
503   ``a = imod(a, b)`` is equivalent to ``a %= b``.
504
505
506.. function:: imul(a, b)
507              __imul__(a, b)
508
509   ``a = imul(a, b)`` is equivalent to ``a *= b``.
510
511
512.. function:: imatmul(a, b)
513              __imatmul__(a, b)
514
515   ``a = imatmul(a, b)`` is equivalent to ``a @= b``.
516
517   .. versionadded:: 3.5
518
519
520.. function:: ior(a, b)
521              __ior__(a, b)
522
523   ``a = ior(a, b)`` is equivalent to ``a |= b``.
524
525
526.. function:: ipow(a, b)
527              __ipow__(a, b)
528
529   ``a = ipow(a, b)`` is equivalent to ``a **= b``.
530
531
532.. function:: irshift(a, b)
533              __irshift__(a, b)
534
535   ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
536
537
538.. function:: isub(a, b)
539              __isub__(a, b)
540
541   ``a = isub(a, b)`` is equivalent to ``a -= b``.
542
543
544.. function:: itruediv(a, b)
545              __itruediv__(a, b)
546
547   ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
548
549
550.. function:: ixor(a, b)
551              __ixor__(a, b)
552
553   ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
554