blob: 2d030615cc3ba5d35da7c2e32b1e48f221b6b68f [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
22operations, mathematical operations, sequence operations, and abstract type
23tests.
24
25The object comparison functions are useful for all objects, and are named after
26the rich comparison operators they support:
27
28
29.. function:: lt(a, b)
30 le(a, b)
31 eq(a, b)
32 ne(a, b)
33 ge(a, b)
34 gt(a, b)
35 __lt__(a, b)
36 __le__(a, b)
37 __eq__(a, b)
38 __ne__(a, b)
39 __ge__(a, b)
40 __gt__(a, b)
41
42 Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
43 equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
44 b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
45 ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
Mark Dickinsonc48d8342009-02-01 14:18:10 +000046 >= b``. Note that these functions can return any value, which may
47 or may not be interpretable as a Boolean value. See
48 :ref:`comparisons` for more information about rich comparisons.
Georg Brandl116aa622007-08-15 14:28:22 +000049
Georg Brandl116aa622007-08-15 14:28:22 +000050
51The logical operations are also generally applicable to all objects, and support
52truth tests, identity tests, and boolean operations:
53
54
Thomas Wouters1b7f8912007-09-19 03:06:30 +000055.. function:: not_(obj)
56 __not__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000057
Thomas Wouters1b7f8912007-09-19 03:06:30 +000058 Return the outcome of :keyword:`not` *obj*. (Note that there is no
Georg Brandl116aa622007-08-15 14:28:22 +000059 :meth:`__not__` method for object instances; only the interpreter core defines
60 this operation. The result is affected by the :meth:`__bool__` and
61 :meth:`__len__` methods.)
62
63
Thomas Wouters1b7f8912007-09-19 03:06:30 +000064.. function:: truth(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000065
Thomas Wouters1b7f8912007-09-19 03:06:30 +000066 Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
Georg Brandl116aa622007-08-15 14:28:22 +000067 equivalent to using the :class:`bool` constructor.
68
69
70.. function:: is_(a, b)
71
72 Return ``a is b``. Tests object identity.
73
Georg Brandl116aa622007-08-15 14:28:22 +000074
75.. function:: is_not(a, b)
76
77 Return ``a is not b``. Tests object identity.
78
Georg Brandl116aa622007-08-15 14:28:22 +000079
80The mathematical and bitwise operations are the most numerous:
81
82
Thomas Wouters1b7f8912007-09-19 03:06:30 +000083.. function:: abs(obj)
84 __abs__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000085
Thomas Wouters1b7f8912007-09-19 03:06:30 +000086 Return the absolute value of *obj*.
Georg Brandl116aa622007-08-15 14:28:22 +000087
88
89.. function:: add(a, b)
90 __add__(a, b)
91
92 Return ``a + b``, for *a* and *b* numbers.
93
94
95.. function:: and_(a, b)
96 __and__(a, b)
97
98 Return the bitwise and of *a* and *b*.
99
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101.. function:: floordiv(a, b)
102 __floordiv__(a, b)
103
104 Return ``a // b``.
105
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000107.. function:: index(a)
108 __index__(a)
109
110 Return *a* converted to an integer. Equivalent to ``a.__index__()``.
111
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000112
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000113.. function:: inv(obj)
114 invert(obj)
115 __inv__(obj)
116 __invert__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000118 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121.. function:: lshift(a, b)
122 __lshift__(a, b)
123
124 Return *a* shifted left by *b*.
125
126
127.. function:: mod(a, b)
128 __mod__(a, b)
129
130 Return ``a % b``.
131
132
133.. function:: mul(a, b)
134 __mul__(a, b)
135
136 Return ``a * b``, for *a* and *b* numbers.
137
138
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000139.. function:: neg(obj)
140 __neg__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000141
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000142 Return *obj* negated (``-obj``).
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144
145.. function:: or_(a, b)
146 __or__(a, b)
147
148 Return the bitwise or of *a* and *b*.
149
150
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151.. function:: pos(obj)
152 __pos__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000154 Return *obj* positive (``+obj``).
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156
157.. function:: pow(a, b)
158 __pow__(a, b)
159
160 Return ``a ** b``, for *a* and *b* numbers.
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162
163.. function:: rshift(a, b)
164 __rshift__(a, b)
165
166 Return *a* shifted right by *b*.
167
168
169.. function:: sub(a, b)
170 __sub__(a, b)
171
172 Return ``a - b``.
173
174
175.. function:: truediv(a, b)
176 __truediv__(a, b)
177
Georg Brandlf6945182008-02-01 11:56:49 +0000178 Return ``a / b`` where 2/3 is .66 rather than 0. This is also known as
179 "true" division.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182.. function:: xor(a, b)
183 __xor__(a, b)
184
185 Return the bitwise exclusive or of *a* and *b*.
186
187
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000188Operations which work with sequences (some of them with mappings too) include:
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190.. function:: concat(a, b)
191 __concat__(a, b)
192
193 Return ``a + b`` for *a* and *b* sequences.
194
195
196.. function:: contains(a, b)
197 __contains__(a, b)
198
199 Return the outcome of the test ``b in a``. Note the reversed operands.
200
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202.. function:: countOf(a, b)
203
204 Return the number of occurrences of *b* in *a*.
205
206
207.. function:: delitem(a, b)
208 __delitem__(a, b)
209
210 Remove the value of *a* at index *b*.
211
Georg Brandl48310cd2009-01-03 21:18:54 +0000212
Georg Brandl116aa622007-08-15 14:28:22 +0000213.. function:: getitem(a, b)
214 __getitem__(a, b)
215
216 Return the value of *a* at index *b*.
217
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219.. function:: indexOf(a, b)
220
221 Return the index of the first of occurrence of *b* in *a*.
222
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224.. function:: setitem(a, b, c)
225 __setitem__(a, b, c)
226
227 Set the value of *a* at index *b* to *c*.
228
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230Many operations have an "in-place" version. The following functions provide a
231more primitive access to in-place operators than the usual syntax does; for
Christian Heimesd8654cf2007-12-02 15:22:16 +0000232example, the :term:`statement` ``x += y`` is equivalent to
233``x = operator.iadd(x, y)``. Another way to put it is to say that
234``z = operator.iadd(x, y)`` is equivalent to the compound statement
235``z = x; z += y``.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. function:: iadd(a, b)
238 __iadd__(a, b)
239
240 ``a = iadd(a, b)`` is equivalent to ``a += b``.
241
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243.. function:: iand(a, b)
244 __iand__(a, b)
245
246 ``a = iand(a, b)`` is equivalent to ``a &= b``.
247
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249.. function:: iconcat(a, b)
250 __iconcat__(a, b)
251
252 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
253
Georg Brandl116aa622007-08-15 14:28:22 +0000254
Georg Brandl116aa622007-08-15 14:28:22 +0000255.. function:: ifloordiv(a, b)
256 __ifloordiv__(a, b)
257
258 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
259
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261.. function:: ilshift(a, b)
262 __ilshift__(a, b)
263
Georg Brandl55ac8f02007-09-01 13:51:09 +0000264 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
267.. function:: imod(a, b)
268 __imod__(a, b)
269
270 ``a = imod(a, b)`` is equivalent to ``a %= b``.
271
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273.. function:: imul(a, b)
274 __imul__(a, b)
275
276 ``a = imul(a, b)`` is equivalent to ``a *= b``.
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279.. function:: ior(a, b)
280 __ior__(a, b)
281
282 ``a = ior(a, b)`` is equivalent to ``a |= b``.
283
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285.. function:: ipow(a, b)
286 __ipow__(a, b)
287
288 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
289
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Georg Brandl116aa622007-08-15 14:28:22 +0000291.. function:: irshift(a, b)
292 __irshift__(a, b)
293
294 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
295
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297.. function:: isub(a, b)
298 __isub__(a, b)
299
300 ``a = isub(a, b)`` is equivalent to ``a -= b``.
301
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303.. function:: itruediv(a, b)
304 __itruediv__(a, b)
305
Georg Brandlf6945182008-02-01 11:56:49 +0000306 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309.. function:: ixor(a, b)
310 __ixor__(a, b)
311
312 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
313
Georg Brandl116aa622007-08-15 14:28:22 +0000314Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
Christian Heimesfe337bf2008-03-23 21:54:12 +0000315their character equivalents.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
Georg Brandl116aa622007-08-15 14:28:22 +0000317 >>> d = {}
318 >>> keys = range(256)
319 >>> vals = map(chr, keys)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000320 >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322.. XXX: find a better, readable, example
323
324The :mod:`operator` module also defines tools for generalized attribute and item
325lookups. These are useful for making fast field extractors as arguments for
326:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
327expect a function argument.
328
329
330.. function:: attrgetter(attr[, args...])
331
332 Return a callable object that fetches *attr* from its operand. If more than one
333 attribute is requested, returns a tuple of attributes. After,
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000334 ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
335 ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000336 b.date)``. Equivalent to::
337
338 def attrgetter(*items):
339 if len(items) == 1:
340 attr = items[0]
341 def g(obj):
342 return resolve_attr(obj, attr)
343 else:
344 def g(obj):
345 return tuple(resolve_att(obj, attr) for attr in items)
346 return g
347
348 def resolve_attr(obj, attr):
349 for name in attr.split("."):
350 obj = getattr(obj, name)
351 return obj
352
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000354 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
355 the call ``f(b)`` returns ``b.date.month``.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357.. function:: itemgetter(item[, args...])
358
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000359 Return a callable object that fetches *item* from its operand using the
360 operand's :meth:`__getitem__` method. If multiple items are specified,
361 returns a tuple of lookup values. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Benjamin Petersonffec8102010-08-21 20:01:28 +0000363 def itemgetter(*items):
364 if len(items) == 1:
365 item = items[0]
366 def g(obj):
367 return obj[item]
368 else:
369 def g(obj):
370 return tuple(obj[item] for item in items)
371 return g
Georg Brandl48310cd2009-01-03 21:18:54 +0000372
373 The items can be any type accepted by the operand's :meth:`__getitem__`
374 method. Dictionaries accept any hashable value. Lists, tuples, and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000375 strings accept an index or a slice:
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Christian Heimesfe337bf2008-03-23 21:54:12 +0000377 >>> itemgetter(1)('ABCDEFG')
378 'B'
379 >>> itemgetter(1,3,5)('ABCDEFG')
380 ('B', 'D', 'F')
381 >>> itemgetter(slice(2,None))('ABCDEFG')
382 'CDEFG'
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000384
385 Example of using :func:`itemgetter` to retrieve specific fields from a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000386 tuple record:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000387
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000388 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
389 >>> getcount = itemgetter(1)
Raymond Hettingerd292a172010-09-01 07:46:54 +0000390 >>> list(map(getcount, inventory))
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000391 [3, 2, 5, 1]
392 >>> sorted(inventory, key=getcount)
393 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000396.. function:: methodcaller(name[, args...])
397
398 Return a callable object that calls the method *name* on its operand. If
399 additional arguments and/or keyword arguments are given, they will be given
400 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
401 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000402 call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
403
404 def methodcaller(name, *args, **kwargs):
405 def caller(obj):
406 return getattr(obj, name)(*args, **kwargs)
407 return caller
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000408
409
Georg Brandl116aa622007-08-15 14:28:22 +0000410.. _operator-map:
411
412Mapping Operators to Functions
413------------------------------
414
415This table shows how abstract operations correspond to operator symbols in the
416Python syntax and the functions in the :mod:`operator` module.
417
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000418+-----------------------+-------------------------+---------------------------------------+
419| Operation | Syntax | Function |
420+=======================+=========================+=======================================+
421| Addition | ``a + b`` | ``add(a, b)`` |
422+-----------------------+-------------------------+---------------------------------------+
423| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
424+-----------------------+-------------------------+---------------------------------------+
425| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
426+-----------------------+-------------------------+---------------------------------------+
427| Division | ``a / b`` | ``div(a, b)`` |
428+-----------------------+-------------------------+---------------------------------------+
429| Division | ``a // b`` | ``floordiv(a, b)`` |
430+-----------------------+-------------------------+---------------------------------------+
431| Bitwise And | ``a & b`` | ``and_(a, b)`` |
432+-----------------------+-------------------------+---------------------------------------+
433| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
434+-----------------------+-------------------------+---------------------------------------+
435| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
436+-----------------------+-------------------------+---------------------------------------+
437| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
438+-----------------------+-------------------------+---------------------------------------+
439| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
440+-----------------------+-------------------------+---------------------------------------+
441| Identity | ``a is b`` | ``is_(a, b)`` |
442+-----------------------+-------------------------+---------------------------------------+
443| Identity | ``a is not b`` | ``is_not(a, b)`` |
444+-----------------------+-------------------------+---------------------------------------+
445| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
446+-----------------------+-------------------------+---------------------------------------+
447| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
448+-----------------------+-------------------------+---------------------------------------+
449| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
450+-----------------------+-------------------------+---------------------------------------+
451| Left Shift | ``a << b`` | ``lshift(a, b)`` |
452+-----------------------+-------------------------+---------------------------------------+
453| Modulo | ``a % b`` | ``mod(a, b)`` |
454+-----------------------+-------------------------+---------------------------------------+
455| Multiplication | ``a * b`` | ``mul(a, b)`` |
456+-----------------------+-------------------------+---------------------------------------+
457| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
458+-----------------------+-------------------------+---------------------------------------+
459| Negation (Logical) | ``not a`` | ``not_(a)`` |
460+-----------------------+-------------------------+---------------------------------------+
461| Positive | ``+ a`` | ``pos(a)`` |
462+-----------------------+-------------------------+---------------------------------------+
463| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
464+-----------------------+-------------------------+---------------------------------------+
465| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
466+-----------------------+-------------------------+---------------------------------------+
467| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
468+-----------------------+-------------------------+---------------------------------------+
469| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
470+-----------------------+-------------------------+---------------------------------------+
471| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
472+-----------------------+-------------------------+---------------------------------------+
473| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
474+-----------------------+-------------------------+---------------------------------------+
475| Subtraction | ``a - b`` | ``sub(a, b)`` |
476+-----------------------+-------------------------+---------------------------------------+
477| Truth Test | ``obj`` | ``truth(obj)`` |
478+-----------------------+-------------------------+---------------------------------------+
479| Ordering | ``a < b`` | ``lt(a, b)`` |
480+-----------------------+-------------------------+---------------------------------------+
481| Ordering | ``a <= b`` | ``le(a, b)`` |
482+-----------------------+-------------------------+---------------------------------------+
483| Equality | ``a == b`` | ``eq(a, b)`` |
484+-----------------------+-------------------------+---------------------------------------+
485| Difference | ``a != b`` | ``ne(a, b)`` |
486+-----------------------+-------------------------+---------------------------------------+
487| Ordering | ``a >= b`` | ``ge(a, b)`` |
488+-----------------------+-------------------------+---------------------------------------+
489| Ordering | ``a > b`` | ``gt(a, b)`` |
490+-----------------------+-------------------------+---------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000491