blob: 87f524137cf24ad035c97d7065d3c520c0e9755a [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
12 from operator import itemgetter
13
Georg Brandl116aa622007-08-15 14:28:22 +000014
15The :mod:`operator` module exports a set of functions implemented in C
16corresponding to the intrinsic operators of Python. For example,
17``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function
18names are those used for special class methods; variants without leading and
19trailing ``__`` are also provided for convenience.
20
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
228
Georg Brandl116aa622007-08-15 14:28:22 +0000229Many operations have an "in-place" version. The following functions provide a
230more primitive access to in-place operators than the usual syntax does; for
Christian Heimesd8654cf2007-12-02 15:22:16 +0000231example, the :term:`statement` ``x += y`` is equivalent to
232``x = operator.iadd(x, y)``. Another way to put it is to say that
233``z = operator.iadd(x, y)`` is equivalent to the compound statement
234``z = x; z += y``.
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236.. function:: iadd(a, b)
237 __iadd__(a, b)
238
239 ``a = iadd(a, b)`` is equivalent to ``a += b``.
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242.. function:: iand(a, b)
243 __iand__(a, b)
244
245 ``a = iand(a, b)`` is equivalent to ``a &= b``.
246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. function:: iconcat(a, b)
249 __iconcat__(a, b)
250
251 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
252
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Georg Brandl116aa622007-08-15 14:28:22 +0000254.. function:: ifloordiv(a, b)
255 __ifloordiv__(a, b)
256
257 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260.. function:: ilshift(a, b)
261 __ilshift__(a, b)
262
Georg Brandl55ac8f02007-09-01 13:51:09 +0000263 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
266.. function:: imod(a, b)
267 __imod__(a, b)
268
269 ``a = imod(a, b)`` is equivalent to ``a %= b``.
270
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272.. function:: imul(a, b)
273 __imul__(a, b)
274
275 ``a = imul(a, b)`` is equivalent to ``a *= b``.
276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278.. function:: ior(a, b)
279 __ior__(a, b)
280
281 ``a = ior(a, b)`` is equivalent to ``a |= b``.
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284.. function:: ipow(a, b)
285 __ipow__(a, b)
286
287 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
288
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Georg Brandl116aa622007-08-15 14:28:22 +0000290.. function:: irshift(a, b)
291 __irshift__(a, b)
292
293 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296.. function:: isub(a, b)
297 __isub__(a, b)
298
299 ``a = isub(a, b)`` is equivalent to ``a -= b``.
300
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302.. function:: itruediv(a, b)
303 __itruediv__(a, b)
304
Georg Brandlf6945182008-02-01 11:56:49 +0000305 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308.. function:: ixor(a, b)
309 __ixor__(a, b)
310
311 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
Christian Heimesfe337bf2008-03-23 21:54:12 +0000314their character equivalents.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Georg Brandl116aa622007-08-15 14:28:22 +0000316 >>> d = {}
317 >>> keys = range(256)
318 >>> vals = map(chr, keys)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000319 >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321.. XXX: find a better, readable, example
322
323The :mod:`operator` module also defines tools for generalized attribute and item
324lookups. These are useful for making fast field extractors as arguments for
325:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
326expect a function argument.
327
328
329.. function:: attrgetter(attr[, args...])
330
331 Return a callable object that fetches *attr* from its operand. If more than one
332 attribute is requested, returns a tuple of attributes. After,
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000333 ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
334 ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000335 b.date)``. Equivalent to::
336
337 def attrgetter(*items):
Antoine Pitroue9745712010-10-31 15:26:04 +0000338 if any(not isinstance(item, str) for item in items):
339 raise TypeError('attribute name must be a string')
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000340 if len(items) == 1:
341 attr = items[0]
342 def g(obj):
343 return resolve_attr(obj, attr)
344 else:
345 def g(obj):
346 return tuple(resolve_att(obj, attr) for attr in items)
347 return g
348
349 def resolve_attr(obj, attr):
350 for name in attr.split("."):
351 obj = getattr(obj, name)
352 return obj
353
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000355 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
356 the call ``f(b)`` returns ``b.date.month``.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358.. function:: itemgetter(item[, args...])
359
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000360 Return a callable object that fetches *item* from its operand using the
361 operand's :meth:`__getitem__` method. If multiple items are specified,
362 returns a tuple of lookup values. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Benjamin Petersonffec8102010-08-21 20:01:28 +0000364 def itemgetter(*items):
365 if len(items) == 1:
366 item = items[0]
367 def g(obj):
368 return obj[item]
369 else:
370 def g(obj):
371 return tuple(obj[item] for item in items)
372 return g
Georg Brandl48310cd2009-01-03 21:18:54 +0000373
374 The items can be any type accepted by the operand's :meth:`__getitem__`
375 method. Dictionaries accept any hashable value. Lists, tuples, and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000376 strings accept an index or a slice:
Georg Brandl116aa622007-08-15 14:28:22 +0000377
Christian Heimesfe337bf2008-03-23 21:54:12 +0000378 >>> itemgetter(1)('ABCDEFG')
379 'B'
380 >>> itemgetter(1,3,5)('ABCDEFG')
381 ('B', 'D', 'F')
382 >>> itemgetter(slice(2,None))('ABCDEFG')
383 'CDEFG'
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000385
386 Example of using :func:`itemgetter` to retrieve specific fields from a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000387 tuple record:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000388
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000389 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
390 >>> getcount = itemgetter(1)
Raymond Hettingerd292a172010-09-01 07:46:54 +0000391 >>> list(map(getcount, inventory))
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000392 [3, 2, 5, 1]
393 >>> sorted(inventory, key=getcount)
394 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000397.. function:: methodcaller(name[, args...])
398
399 Return a callable object that calls the method *name* on its operand. If
400 additional arguments and/or keyword arguments are given, they will be given
401 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
402 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000403 call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
404
405 def methodcaller(name, *args, **kwargs):
406 def caller(obj):
407 return getattr(obj, name)(*args, **kwargs)
408 return caller
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000409
410
Georg Brandl116aa622007-08-15 14:28:22 +0000411.. _operator-map:
412
413Mapping Operators to Functions
414------------------------------
415
416This table shows how abstract operations correspond to operator symbols in the
417Python syntax and the functions in the :mod:`operator` module.
418
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000419+-----------------------+-------------------------+---------------------------------------+
420| Operation | Syntax | Function |
421+=======================+=========================+=======================================+
422| Addition | ``a + b`` | ``add(a, b)`` |
423+-----------------------+-------------------------+---------------------------------------+
424| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
425+-----------------------+-------------------------+---------------------------------------+
426| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
427+-----------------------+-------------------------+---------------------------------------+
428| Division | ``a / b`` | ``div(a, b)`` |
429+-----------------------+-------------------------+---------------------------------------+
430| Division | ``a // b`` | ``floordiv(a, b)`` |
431+-----------------------+-------------------------+---------------------------------------+
432| Bitwise And | ``a & b`` | ``and_(a, b)`` |
433+-----------------------+-------------------------+---------------------------------------+
434| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
435+-----------------------+-------------------------+---------------------------------------+
436| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
437+-----------------------+-------------------------+---------------------------------------+
438| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
439+-----------------------+-------------------------+---------------------------------------+
440| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
441+-----------------------+-------------------------+---------------------------------------+
442| Identity | ``a is b`` | ``is_(a, b)`` |
443+-----------------------+-------------------------+---------------------------------------+
444| Identity | ``a is not b`` | ``is_not(a, b)`` |
445+-----------------------+-------------------------+---------------------------------------+
446| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
447+-----------------------+-------------------------+---------------------------------------+
448| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
449+-----------------------+-------------------------+---------------------------------------+
450| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
451+-----------------------+-------------------------+---------------------------------------+
452| Left Shift | ``a << b`` | ``lshift(a, b)`` |
453+-----------------------+-------------------------+---------------------------------------+
454| Modulo | ``a % b`` | ``mod(a, b)`` |
455+-----------------------+-------------------------+---------------------------------------+
456| Multiplication | ``a * b`` | ``mul(a, b)`` |
457+-----------------------+-------------------------+---------------------------------------+
458| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
459+-----------------------+-------------------------+---------------------------------------+
460| Negation (Logical) | ``not a`` | ``not_(a)`` |
461+-----------------------+-------------------------+---------------------------------------+
462| Positive | ``+ a`` | ``pos(a)`` |
463+-----------------------+-------------------------+---------------------------------------+
464| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
465+-----------------------+-------------------------+---------------------------------------+
466| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
467+-----------------------+-------------------------+---------------------------------------+
468| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
469+-----------------------+-------------------------+---------------------------------------+
470| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
471+-----------------------+-------------------------+---------------------------------------+
472| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
473+-----------------------+-------------------------+---------------------------------------+
474| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
475+-----------------------+-------------------------+---------------------------------------+
476| Subtraction | ``a - b`` | ``sub(a, b)`` |
477+-----------------------+-------------------------+---------------------------------------+
478| Truth Test | ``obj`` | ``truth(obj)`` |
479+-----------------------+-------------------------+---------------------------------------+
480| Ordering | ``a < b`` | ``lt(a, b)`` |
481+-----------------------+-------------------------+---------------------------------------+
482| Ordering | ``a <= b`` | ``le(a, b)`` |
483+-----------------------+-------------------------+---------------------------------------+
484| Equality | ``a == b`` | ``eq(a, b)`` |
485+-----------------------+-------------------------+---------------------------------------+
486| Difference | ``a != b`` | ``ne(a, b)`` |
487+-----------------------+-------------------------+---------------------------------------+
488| Ordering | ``a >= b`` | ``ge(a, b)`` |
489+-----------------------+-------------------------+---------------------------------------+
490| Ordering | ``a > b`` | ``gt(a, b)`` |
491+-----------------------+-------------------------+---------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000492