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