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