blob: 877a79069b65a07455f2f2a7844f512f4dbe0d18 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001: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
Christian Heimesfe337bf2008-03-23 21:54:12 +00009.. testsetup::
Georg Brandl48310cd2009-01-03 21:18:54 +000010
Christian Heimesfe337bf2008-03-23 21:54:12 +000011 import operator
Alexander Belopolsky287d1fd2011-01-12 16:37:14 +000012 from operator import itemgetter, iadd
Christian Heimesfe337bf2008-03-23 21:54:12 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014
Benjamin Peterson0f1e3ac2011-12-20 10:12:41 -060015The :mod:`operator` module exports a set of efficient functions corresponding to
16the intrinsic operators of Python. For example, ``operator.add(x, y)`` is
Benjamin Peterson1c92cfe2011-12-19 16:41:11 -050017equivalent to the expression ``x+y``. The function names are those used for
18special class methods; variants without leading and trailing ``__`` are also
19provided for convenience.
Georg Brandl116aa622007-08-15 14:28:22 +000020
21The functions fall into categories that perform object comparisons, logical
Georg Brandlb30f3302011-01-06 09:23:56 +000022operations, mathematical operations and sequence operations.
Georg Brandl116aa622007-08-15 14:28:22 +000023
24The object comparison functions are useful for all objects, and are named after
25the rich comparison operators they support:
26
27
28.. function:: lt(a, b)
29 le(a, b)
30 eq(a, b)
31 ne(a, b)
32 ge(a, b)
33 gt(a, b)
34 __lt__(a, b)
35 __le__(a, b)
36 __eq__(a, b)
37 __ne__(a, b)
38 __ge__(a, b)
39 __gt__(a, b)
40
41 Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
42 equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
43 b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
44 ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
Mark Dickinsonc48d8342009-02-01 14:18:10 +000045 >= b``. Note that these functions can return any value, which may
46 or may not be interpretable as a Boolean value. See
47 :ref:`comparisons` for more information about rich comparisons.
Georg Brandl116aa622007-08-15 14:28:22 +000048
Georg Brandl116aa622007-08-15 14:28:22 +000049
50The logical operations are also generally applicable to all objects, and support
51truth tests, identity tests, and boolean operations:
52
53
Thomas Wouters1b7f8912007-09-19 03:06:30 +000054.. function:: not_(obj)
55 __not__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000056
Thomas Wouters1b7f8912007-09-19 03:06:30 +000057 Return the outcome of :keyword:`not` *obj*. (Note that there is no
Georg Brandl116aa622007-08-15 14:28:22 +000058 :meth:`__not__` method for object instances; only the interpreter core defines
59 this operation. The result is affected by the :meth:`__bool__` and
60 :meth:`__len__` methods.)
61
62
Thomas Wouters1b7f8912007-09-19 03:06:30 +000063.. function:: truth(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000064
Thomas Wouters1b7f8912007-09-19 03:06:30 +000065 Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
Georg Brandl116aa622007-08-15 14:28:22 +000066 equivalent to using the :class:`bool` constructor.
67
68
69.. function:: is_(a, b)
70
71 Return ``a is b``. Tests object identity.
72
Georg Brandl116aa622007-08-15 14:28:22 +000073
74.. function:: is_not(a, b)
75
76 Return ``a is not b``. Tests object identity.
77
Georg Brandl116aa622007-08-15 14:28:22 +000078
79The mathematical and bitwise operations are the most numerous:
80
81
Thomas Wouters1b7f8912007-09-19 03:06:30 +000082.. function:: abs(obj)
83 __abs__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000084
Thomas Wouters1b7f8912007-09-19 03:06:30 +000085 Return the absolute value of *obj*.
Georg Brandl116aa622007-08-15 14:28:22 +000086
87
88.. function:: add(a, b)
89 __add__(a, b)
90
91 Return ``a + b``, for *a* and *b* numbers.
92
93
94.. function:: and_(a, b)
95 __and__(a, b)
96
97 Return the bitwise and of *a* and *b*.
98
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100.. function:: floordiv(a, b)
101 __floordiv__(a, b)
102
103 Return ``a // b``.
104
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000106.. function:: index(a)
107 __index__(a)
108
109 Return *a* converted to an integer. Equivalent to ``a.__index__()``.
110
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000111
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000112.. function:: inv(obj)
113 invert(obj)
114 __inv__(obj)
115 __invert__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000116
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000117 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120.. function:: lshift(a, b)
121 __lshift__(a, b)
122
123 Return *a* shifted left by *b*.
124
125
126.. function:: mod(a, b)
127 __mod__(a, b)
128
129 Return ``a % b``.
130
131
132.. function:: mul(a, b)
133 __mul__(a, b)
134
135 Return ``a * b``, for *a* and *b* numbers.
136
137
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000138.. function:: neg(obj)
139 __neg__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000141 Return *obj* negated (``-obj``).
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143
144.. function:: or_(a, b)
145 __or__(a, b)
146
147 Return the bitwise or of *a* and *b*.
148
149
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000150.. function:: pos(obj)
151 __pos__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000152
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000153 Return *obj* positive (``+obj``).
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155
156.. function:: pow(a, b)
157 __pow__(a, b)
158
159 Return ``a ** b``, for *a* and *b* numbers.
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162.. function:: rshift(a, b)
163 __rshift__(a, b)
164
165 Return *a* shifted right by *b*.
166
167
168.. function:: sub(a, b)
169 __sub__(a, b)
170
171 Return ``a - b``.
172
173
174.. function:: truediv(a, b)
175 __truediv__(a, b)
176
Georg Brandlf6945182008-02-01 11:56:49 +0000177 Return ``a / b`` where 2/3 is .66 rather than 0. This is also known as
178 "true" division.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181.. function:: xor(a, b)
182 __xor__(a, b)
183
184 Return the bitwise exclusive or of *a* and *b*.
185
186
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000187Operations which work with sequences (some of them with mappings too) include:
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189.. function:: concat(a, b)
190 __concat__(a, b)
191
192 Return ``a + b`` for *a* and *b* sequences.
193
194
195.. function:: contains(a, b)
196 __contains__(a, b)
197
198 Return the outcome of the test ``b in a``. Note the reversed operands.
199
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201.. function:: countOf(a, b)
202
203 Return the number of occurrences of *b* in *a*.
204
205
206.. function:: delitem(a, b)
207 __delitem__(a, b)
208
209 Remove the value of *a* at index *b*.
210
Georg Brandl48310cd2009-01-03 21:18:54 +0000211
Georg Brandl116aa622007-08-15 14:28:22 +0000212.. function:: getitem(a, b)
213 __getitem__(a, b)
214
215 Return the value of *a* at index *b*.
216
217
Georg Brandl116aa622007-08-15 14:28:22 +0000218.. function:: indexOf(a, b)
219
220 Return the index of the first of occurrence of *b* in *a*.
221
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223.. function:: setitem(a, b, c)
224 __setitem__(a, b, c)
225
226 Set the value of *a* at index *b* to *c*.
227
Georg Brandl116aa622007-08-15 14:28:22 +0000228Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
Christian Heimesfe337bf2008-03-23 21:54:12 +0000229their character equivalents.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Georg Brandl116aa622007-08-15 14:28:22 +0000231 >>> d = {}
232 >>> keys = range(256)
233 >>> vals = map(chr, keys)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000234 >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236.. XXX: find a better, readable, example
237
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200238.. function:: length_hint(obj, default=0)
239
240 Return an estimated length for the object *o*. First trying to return its
Ezio Melottie12dc282012-10-07 12:09:36 +0300241 actual length, then an estimate using :meth:`object.__length_hint__`, and
242 finally returning the default value.
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200243
Armin Ronacher74b38b12012-10-07 10:29:32 +0200244 .. versionadded:: 3.4
245
Georg Brandl116aa622007-08-15 14:28:22 +0000246The :mod:`operator` module also defines tools for generalized attribute and item
247lookups. These are useful for making fast field extractors as arguments for
248:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
249expect a function argument.
250
251
252.. function:: attrgetter(attr[, args...])
253
254 Return a callable object that fetches *attr* from its operand. If more than one
255 attribute is requested, returns a tuple of attributes. After,
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000256 ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
257 ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000258 b.date)``. Equivalent to::
259
260 def attrgetter(*items):
Antoine Pitroue9745712010-10-31 15:26:04 +0000261 if any(not isinstance(item, str) for item in items):
262 raise TypeError('attribute name must be a string')
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000263 if len(items) == 1:
264 attr = items[0]
265 def g(obj):
266 return resolve_attr(obj, attr)
267 else:
268 def g(obj):
269 return tuple(resolve_att(obj, attr) for attr in items)
270 return g
271
272 def resolve_attr(obj, attr):
273 for name in attr.split("."):
274 obj = getattr(obj, name)
275 return obj
276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000278 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
279 the call ``f(b)`` returns ``b.date.month``.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281.. function:: itemgetter(item[, args...])
282
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000283 Return a callable object that fetches *item* from its operand using the
284 operand's :meth:`__getitem__` method. If multiple items are specified,
285 returns a tuple of lookup values. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Benjamin Petersonffec8102010-08-21 20:01:28 +0000287 def itemgetter(*items):
288 if len(items) == 1:
289 item = items[0]
290 def g(obj):
291 return obj[item]
292 else:
293 def g(obj):
294 return tuple(obj[item] for item in items)
295 return g
Georg Brandl48310cd2009-01-03 21:18:54 +0000296
297 The items can be any type accepted by the operand's :meth:`__getitem__`
298 method. Dictionaries accept any hashable value. Lists, tuples, and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000299 strings accept an index or a slice:
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Christian Heimesfe337bf2008-03-23 21:54:12 +0000301 >>> itemgetter(1)('ABCDEFG')
302 'B'
303 >>> itemgetter(1,3,5)('ABCDEFG')
304 ('B', 'D', 'F')
305 >>> itemgetter(slice(2,None))('ABCDEFG')
306 'CDEFG'
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000308
309 Example of using :func:`itemgetter` to retrieve specific fields from a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000310 tuple record:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000311
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000312 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
313 >>> getcount = itemgetter(1)
Raymond Hettingerd292a172010-09-01 07:46:54 +0000314 >>> list(map(getcount, inventory))
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000315 [3, 2, 5, 1]
316 >>> sorted(inventory, key=getcount)
317 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000320.. function:: methodcaller(name[, args...])
321
322 Return a callable object that calls the method *name* on its operand. If
323 additional arguments and/or keyword arguments are given, they will be given
324 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
325 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000326 call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
327
328 def methodcaller(name, *args, **kwargs):
329 def caller(obj):
330 return getattr(obj, name)(*args, **kwargs)
331 return caller
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000332
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334.. _operator-map:
335
336Mapping Operators to Functions
337------------------------------
338
339This table shows how abstract operations correspond to operator symbols in the
340Python syntax and the functions in the :mod:`operator` module.
341
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000342+-----------------------+-------------------------+---------------------------------------+
343| Operation | Syntax | Function |
344+=======================+=========================+=======================================+
345| Addition | ``a + b`` | ``add(a, b)`` |
346+-----------------------+-------------------------+---------------------------------------+
347| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
348+-----------------------+-------------------------+---------------------------------------+
349| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
350+-----------------------+-------------------------+---------------------------------------+
Sandro Tosi83c48822012-02-28 22:28:28 +0100351| Division | ``a / b`` | ``truediv(a, b)`` |
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000352+-----------------------+-------------------------+---------------------------------------+
353| Division | ``a // b`` | ``floordiv(a, b)`` |
354+-----------------------+-------------------------+---------------------------------------+
355| Bitwise And | ``a & b`` | ``and_(a, b)`` |
356+-----------------------+-------------------------+---------------------------------------+
357| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
358+-----------------------+-------------------------+---------------------------------------+
359| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
360+-----------------------+-------------------------+---------------------------------------+
361| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
362+-----------------------+-------------------------+---------------------------------------+
363| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
364+-----------------------+-------------------------+---------------------------------------+
365| Identity | ``a is b`` | ``is_(a, b)`` |
366+-----------------------+-------------------------+---------------------------------------+
367| Identity | ``a is not b`` | ``is_not(a, b)`` |
368+-----------------------+-------------------------+---------------------------------------+
369| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
370+-----------------------+-------------------------+---------------------------------------+
371| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
372+-----------------------+-------------------------+---------------------------------------+
373| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
374+-----------------------+-------------------------+---------------------------------------+
375| Left Shift | ``a << b`` | ``lshift(a, b)`` |
376+-----------------------+-------------------------+---------------------------------------+
377| Modulo | ``a % b`` | ``mod(a, b)`` |
378+-----------------------+-------------------------+---------------------------------------+
379| Multiplication | ``a * b`` | ``mul(a, b)`` |
380+-----------------------+-------------------------+---------------------------------------+
381| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
382+-----------------------+-------------------------+---------------------------------------+
383| Negation (Logical) | ``not a`` | ``not_(a)`` |
384+-----------------------+-------------------------+---------------------------------------+
385| Positive | ``+ a`` | ``pos(a)`` |
386+-----------------------+-------------------------+---------------------------------------+
387| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
388+-----------------------+-------------------------+---------------------------------------+
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000389| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
390+-----------------------+-------------------------+---------------------------------------+
391| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
392+-----------------------+-------------------------+---------------------------------------+
393| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
394+-----------------------+-------------------------+---------------------------------------+
395| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
396+-----------------------+-------------------------+---------------------------------------+
397| Subtraction | ``a - b`` | ``sub(a, b)`` |
398+-----------------------+-------------------------+---------------------------------------+
399| Truth Test | ``obj`` | ``truth(obj)`` |
400+-----------------------+-------------------------+---------------------------------------+
401| Ordering | ``a < b`` | ``lt(a, b)`` |
402+-----------------------+-------------------------+---------------------------------------+
403| Ordering | ``a <= b`` | ``le(a, b)`` |
404+-----------------------+-------------------------+---------------------------------------+
405| Equality | ``a == b`` | ``eq(a, b)`` |
406+-----------------------+-------------------------+---------------------------------------+
407| Difference | ``a != b`` | ``ne(a, b)`` |
408+-----------------------+-------------------------+---------------------------------------+
409| Ordering | ``a >= b`` | ``ge(a, b)`` |
410+-----------------------+-------------------------+---------------------------------------+
411| Ordering | ``a > b`` | ``gt(a, b)`` |
412+-----------------------+-------------------------+---------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Raymond Hettinger83b1ab02011-01-08 10:26:53 +0000414Inplace Operators
Sandro Tosi3f7d1d32012-06-01 20:23:20 +0200415-----------------
Raymond Hettinger83b1ab02011-01-08 10:26:53 +0000416
417Many operations have an "in-place" version. Listed below are functions
418providing a more primitive access to in-place operators than the usual syntax
419does; for example, the :term:`statement` ``x += y`` is equivalent to
420``x = operator.iadd(x, y)``. Another way to put it is to say that
421``z = operator.iadd(x, y)`` is equivalent to the compound statement
422``z = x; z += y``.
423
424In those examples, note that when an in-place method is called, the computation
425and assignment are performed in two separate steps. The in-place functions
426listed below only do the first step, calling the in-place method. The second
427step, assignment, is not handled.
428
429For immutable targets such as strings, numbers, and tuples, the updated
430value is computed, but not assigned back to the input variable:
431
432>>> a = 'hello'
433>>> iadd(a, ' world')
434'hello world'
435>>> a
436'hello'
437
438For mutable targets such as lists and dictionaries, the inplace method
439will perform the update, so no subsequent assignment is necessary:
440
441>>> s = ['h', 'e', 'l', 'l', 'o']
442>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
443['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
444>>> s
445['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
446
447.. function:: iadd(a, b)
448 __iadd__(a, b)
449
450 ``a = iadd(a, b)`` is equivalent to ``a += b``.
451
452
453.. function:: iand(a, b)
454 __iand__(a, b)
455
456 ``a = iand(a, b)`` is equivalent to ``a &= b``.
457
458
459.. function:: iconcat(a, b)
460 __iconcat__(a, b)
461
462 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
463
464
465.. function:: ifloordiv(a, b)
466 __ifloordiv__(a, b)
467
468 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
469
470
471.. function:: ilshift(a, b)
472 __ilshift__(a, b)
473
474 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
475
476
477.. function:: imod(a, b)
478 __imod__(a, b)
479
480 ``a = imod(a, b)`` is equivalent to ``a %= b``.
481
482
483.. function:: imul(a, b)
484 __imul__(a, b)
485
486 ``a = imul(a, b)`` is equivalent to ``a *= b``.
487
488
489.. function:: ior(a, b)
490 __ior__(a, b)
491
492 ``a = ior(a, b)`` is equivalent to ``a |= b``.
493
494
495.. function:: ipow(a, b)
496 __ipow__(a, b)
497
498 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
499
500
501.. function:: irshift(a, b)
502 __irshift__(a, b)
503
504 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
505
506
507.. function:: isub(a, b)
508 __isub__(a, b)
509
510 ``a = isub(a, b)`` is equivalent to ``a -= b``.
511
512
513.. function:: itruediv(a, b)
514 __itruediv__(a, b)
515
516 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
517
518
519.. function:: ixor(a, b)
520 __ixor__(a, b)
521
522 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.