blob: 3860880bf0ec110f8ff8acee19022c5ecdbd8962 [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
238The :mod:`operator` module also defines tools for generalized attribute and item
239lookups. These are useful for making fast field extractors as arguments for
240:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
241expect a function argument.
242
243
244.. function:: attrgetter(attr[, args...])
245
246 Return a callable object that fetches *attr* from its operand. If more than one
247 attribute is requested, returns a tuple of attributes. After,
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000248 ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
249 ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000250 b.date)``. Equivalent to::
251
252 def attrgetter(*items):
Antoine Pitroue9745712010-10-31 15:26:04 +0000253 if any(not isinstance(item, str) for item in items):
254 raise TypeError('attribute name must be a string')
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000255 if len(items) == 1:
256 attr = items[0]
257 def g(obj):
258 return resolve_attr(obj, attr)
259 else:
260 def g(obj):
261 return tuple(resolve_att(obj, attr) for attr in items)
262 return g
263
264 def resolve_attr(obj, attr):
265 for name in attr.split("."):
266 obj = getattr(obj, name)
267 return obj
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000270 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
271 the call ``f(b)`` returns ``b.date.month``.
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273.. function:: itemgetter(item[, args...])
274
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000275 Return a callable object that fetches *item* from its operand using the
276 operand's :meth:`__getitem__` method. If multiple items are specified,
277 returns a tuple of lookup values. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Benjamin Petersonffec8102010-08-21 20:01:28 +0000279 def itemgetter(*items):
280 if len(items) == 1:
281 item = items[0]
282 def g(obj):
283 return obj[item]
284 else:
285 def g(obj):
286 return tuple(obj[item] for item in items)
287 return g
Georg Brandl48310cd2009-01-03 21:18:54 +0000288
289 The items can be any type accepted by the operand's :meth:`__getitem__`
290 method. Dictionaries accept any hashable value. Lists, tuples, and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000291 strings accept an index or a slice:
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Christian Heimesfe337bf2008-03-23 21:54:12 +0000293 >>> itemgetter(1)('ABCDEFG')
294 'B'
295 >>> itemgetter(1,3,5)('ABCDEFG')
296 ('B', 'D', 'F')
297 >>> itemgetter(slice(2,None))('ABCDEFG')
298 'CDEFG'
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000300
301 Example of using :func:`itemgetter` to retrieve specific fields from a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000302 tuple record:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000303
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000304 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
305 >>> getcount = itemgetter(1)
Raymond Hettingerd292a172010-09-01 07:46:54 +0000306 >>> list(map(getcount, inventory))
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000307 [3, 2, 5, 1]
308 >>> sorted(inventory, key=getcount)
309 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000312.. function:: methodcaller(name[, args...])
313
314 Return a callable object that calls the method *name* on its operand. If
315 additional arguments and/or keyword arguments are given, they will be given
316 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
317 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000318 call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
319
320 def methodcaller(name, *args, **kwargs):
321 def caller(obj):
322 return getattr(obj, name)(*args, **kwargs)
323 return caller
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000324
325
Georg Brandl116aa622007-08-15 14:28:22 +0000326.. _operator-map:
327
328Mapping Operators to Functions
329------------------------------
330
331This table shows how abstract operations correspond to operator symbols in the
332Python syntax and the functions in the :mod:`operator` module.
333
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000334+-----------------------+-------------------------+---------------------------------------+
335| Operation | Syntax | Function |
336+=======================+=========================+=======================================+
337| Addition | ``a + b`` | ``add(a, b)`` |
338+-----------------------+-------------------------+---------------------------------------+
339| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
340+-----------------------+-------------------------+---------------------------------------+
341| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
342+-----------------------+-------------------------+---------------------------------------+
Sandro Tosi83c48822012-02-28 22:28:28 +0100343| Division | ``a / b`` | ``truediv(a, b)`` |
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000344+-----------------------+-------------------------+---------------------------------------+
345| Division | ``a // b`` | ``floordiv(a, b)`` |
346+-----------------------+-------------------------+---------------------------------------+
347| Bitwise And | ``a & b`` | ``and_(a, b)`` |
348+-----------------------+-------------------------+---------------------------------------+
349| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
350+-----------------------+-------------------------+---------------------------------------+
351| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
352+-----------------------+-------------------------+---------------------------------------+
353| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
354+-----------------------+-------------------------+---------------------------------------+
355| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
356+-----------------------+-------------------------+---------------------------------------+
357| Identity | ``a is b`` | ``is_(a, b)`` |
358+-----------------------+-------------------------+---------------------------------------+
359| Identity | ``a is not b`` | ``is_not(a, b)`` |
360+-----------------------+-------------------------+---------------------------------------+
361| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
362+-----------------------+-------------------------+---------------------------------------+
363| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
364+-----------------------+-------------------------+---------------------------------------+
365| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
366+-----------------------+-------------------------+---------------------------------------+
367| Left Shift | ``a << b`` | ``lshift(a, b)`` |
368+-----------------------+-------------------------+---------------------------------------+
369| Modulo | ``a % b`` | ``mod(a, b)`` |
370+-----------------------+-------------------------+---------------------------------------+
371| Multiplication | ``a * b`` | ``mul(a, b)`` |
372+-----------------------+-------------------------+---------------------------------------+
373| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
374+-----------------------+-------------------------+---------------------------------------+
375| Negation (Logical) | ``not a`` | ``not_(a)`` |
376+-----------------------+-------------------------+---------------------------------------+
377| Positive | ``+ a`` | ``pos(a)`` |
378+-----------------------+-------------------------+---------------------------------------+
379| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
380+-----------------------+-------------------------+---------------------------------------+
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000381| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
382+-----------------------+-------------------------+---------------------------------------+
383| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
384+-----------------------+-------------------------+---------------------------------------+
385| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
386+-----------------------+-------------------------+---------------------------------------+
387| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
388+-----------------------+-------------------------+---------------------------------------+
389| Subtraction | ``a - b`` | ``sub(a, b)`` |
390+-----------------------+-------------------------+---------------------------------------+
391| Truth Test | ``obj`` | ``truth(obj)`` |
392+-----------------------+-------------------------+---------------------------------------+
393| Ordering | ``a < b`` | ``lt(a, b)`` |
394+-----------------------+-------------------------+---------------------------------------+
395| Ordering | ``a <= b`` | ``le(a, b)`` |
396+-----------------------+-------------------------+---------------------------------------+
397| Equality | ``a == b`` | ``eq(a, b)`` |
398+-----------------------+-------------------------+---------------------------------------+
399| Difference | ``a != b`` | ``ne(a, b)`` |
400+-----------------------+-------------------------+---------------------------------------+
401| Ordering | ``a >= b`` | ``ge(a, b)`` |
402+-----------------------+-------------------------+---------------------------------------+
403| Ordering | ``a > b`` | ``gt(a, b)`` |
404+-----------------------+-------------------------+---------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000405
Raymond Hettinger83b1ab02011-01-08 10:26:53 +0000406Inplace Operators
Sandro Tosi3f7d1d32012-06-01 20:23:20 +0200407-----------------
Raymond Hettinger83b1ab02011-01-08 10:26:53 +0000408
409Many operations have an "in-place" version. Listed below are functions
410providing a more primitive access to in-place operators than the usual syntax
411does; for example, the :term:`statement` ``x += y`` is equivalent to
412``x = operator.iadd(x, y)``. Another way to put it is to say that
413``z = operator.iadd(x, y)`` is equivalent to the compound statement
414``z = x; z += y``.
415
416In those examples, note that when an in-place method is called, the computation
417and assignment are performed in two separate steps. The in-place functions
418listed below only do the first step, calling the in-place method. The second
419step, assignment, is not handled.
420
421For immutable targets such as strings, numbers, and tuples, the updated
422value is computed, but not assigned back to the input variable:
423
424>>> a = 'hello'
425>>> iadd(a, ' world')
426'hello world'
427>>> a
428'hello'
429
430For mutable targets such as lists and dictionaries, the inplace method
431will perform the update, so no subsequent assignment is necessary:
432
433>>> s = ['h', 'e', 'l', 'l', 'o']
434>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
435['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
436>>> s
437['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
438
439.. function:: iadd(a, b)
440 __iadd__(a, b)
441
442 ``a = iadd(a, b)`` is equivalent to ``a += b``.
443
444
445.. function:: iand(a, b)
446 __iand__(a, b)
447
448 ``a = iand(a, b)`` is equivalent to ``a &= b``.
449
450
451.. function:: iconcat(a, b)
452 __iconcat__(a, b)
453
454 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
455
456
457.. function:: ifloordiv(a, b)
458 __ifloordiv__(a, b)
459
460 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
461
462
463.. function:: ilshift(a, b)
464 __ilshift__(a, b)
465
466 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
467
468
469.. function:: imod(a, b)
470 __imod__(a, b)
471
472 ``a = imod(a, b)`` is equivalent to ``a %= b``.
473
474
475.. function:: imul(a, b)
476 __imul__(a, b)
477
478 ``a = imul(a, b)`` is equivalent to ``a *= b``.
479
480
481.. function:: ior(a, b)
482 __ior__(a, b)
483
484 ``a = ior(a, b)`` is equivalent to ``a |= b``.
485
486
487.. function:: ipow(a, b)
488 __ipow__(a, b)
489
490 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
491
492
493.. function:: irshift(a, b)
494 __irshift__(a, b)
495
496 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
497
498
499.. function:: isub(a, b)
500 __isub__(a, b)
501
502 ``a = isub(a, b)`` is equivalent to ``a -= b``.
503
504
505.. function:: itruediv(a, b)
506 __itruediv__(a, b)
507
508 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
509
510
511.. function:: ixor(a, b)
512 __ixor__(a, b)
513
514 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.