blob: efefaa690ea68d474cb31c19e3cf0da68e6139d3 [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):
Antoine Pitroue9745712010-10-31 15:26:04 +0000339 if any(not isinstance(item, str) for item in items):
340 raise TypeError('attribute name must be a string')
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000341 if len(items) == 1:
342 attr = items[0]
343 def g(obj):
344 return resolve_attr(obj, attr)
345 else:
346 def g(obj):
347 return tuple(resolve_att(obj, attr) for attr in items)
348 return g
349
350 def resolve_attr(obj, attr):
351 for name in attr.split("."):
352 obj = getattr(obj, name)
353 return obj
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000356 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
357 the call ``f(b)`` returns ``b.date.month``.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359.. function:: itemgetter(item[, args...])
360
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000361 Return a callable object that fetches *item* from its operand using the
362 operand's :meth:`__getitem__` method. If multiple items are specified,
363 returns a tuple of lookup values. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Benjamin Petersonffec8102010-08-21 20:01:28 +0000365 def itemgetter(*items):
366 if len(items) == 1:
367 item = items[0]
368 def g(obj):
369 return obj[item]
370 else:
371 def g(obj):
372 return tuple(obj[item] for item in items)
373 return g
Georg Brandl48310cd2009-01-03 21:18:54 +0000374
375 The items can be any type accepted by the operand's :meth:`__getitem__`
376 method. Dictionaries accept any hashable value. Lists, tuples, and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000377 strings accept an index or a slice:
Georg Brandl116aa622007-08-15 14:28:22 +0000378
Christian Heimesfe337bf2008-03-23 21:54:12 +0000379 >>> itemgetter(1)('ABCDEFG')
380 'B'
381 >>> itemgetter(1,3,5)('ABCDEFG')
382 ('B', 'D', 'F')
383 >>> itemgetter(slice(2,None))('ABCDEFG')
384 'CDEFG'
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000386
387 Example of using :func:`itemgetter` to retrieve specific fields from a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000388 tuple record:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000389
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000390 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
391 >>> getcount = itemgetter(1)
Raymond Hettingerd292a172010-09-01 07:46:54 +0000392 >>> list(map(getcount, inventory))
Benjamin Petersonc16f8b32010-08-21 20:03:15 +0000393 [3, 2, 5, 1]
394 >>> sorted(inventory, key=getcount)
395 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000398.. function:: methodcaller(name[, args...])
399
400 Return a callable object that calls the method *name* on its operand. If
401 additional arguments and/or keyword arguments are given, they will be given
402 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
403 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
Benjamin Peterson2d55e2a2010-08-21 20:08:36 +0000404 call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
405
406 def methodcaller(name, *args, **kwargs):
407 def caller(obj):
408 return getattr(obj, name)(*args, **kwargs)
409 return caller
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000410
411
Georg Brandl116aa622007-08-15 14:28:22 +0000412.. _operator-map:
413
414Mapping Operators to Functions
415------------------------------
416
417This table shows how abstract operations correspond to operator symbols in the
418Python syntax and the functions in the :mod:`operator` module.
419
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000420+-----------------------+-------------------------+---------------------------------------+
421| Operation | Syntax | Function |
422+=======================+=========================+=======================================+
423| Addition | ``a + b`` | ``add(a, b)`` |
424+-----------------------+-------------------------+---------------------------------------+
425| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
426+-----------------------+-------------------------+---------------------------------------+
427| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
428+-----------------------+-------------------------+---------------------------------------+
429| Division | ``a / b`` | ``div(a, b)`` |
430+-----------------------+-------------------------+---------------------------------------+
431| Division | ``a // b`` | ``floordiv(a, b)`` |
432+-----------------------+-------------------------+---------------------------------------+
433| Bitwise And | ``a & b`` | ``and_(a, b)`` |
434+-----------------------+-------------------------+---------------------------------------+
435| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
436+-----------------------+-------------------------+---------------------------------------+
437| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
438+-----------------------+-------------------------+---------------------------------------+
439| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
440+-----------------------+-------------------------+---------------------------------------+
441| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
442+-----------------------+-------------------------+---------------------------------------+
443| Identity | ``a is b`` | ``is_(a, b)`` |
444+-----------------------+-------------------------+---------------------------------------+
445| Identity | ``a is not b`` | ``is_not(a, b)`` |
446+-----------------------+-------------------------+---------------------------------------+
447| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
448+-----------------------+-------------------------+---------------------------------------+
449| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
450+-----------------------+-------------------------+---------------------------------------+
451| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
452+-----------------------+-------------------------+---------------------------------------+
453| Left Shift | ``a << b`` | ``lshift(a, b)`` |
454+-----------------------+-------------------------+---------------------------------------+
455| Modulo | ``a % b`` | ``mod(a, b)`` |
456+-----------------------+-------------------------+---------------------------------------+
457| Multiplication | ``a * b`` | ``mul(a, b)`` |
458+-----------------------+-------------------------+---------------------------------------+
459| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
460+-----------------------+-------------------------+---------------------------------------+
461| Negation (Logical) | ``not a`` | ``not_(a)`` |
462+-----------------------+-------------------------+---------------------------------------+
463| Positive | ``+ a`` | ``pos(a)`` |
464+-----------------------+-------------------------+---------------------------------------+
465| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
466+-----------------------+-------------------------+---------------------------------------+
467| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
468+-----------------------+-------------------------+---------------------------------------+
469| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
470+-----------------------+-------------------------+---------------------------------------+
471| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
472+-----------------------+-------------------------+---------------------------------------+
473| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
474+-----------------------+-------------------------+---------------------------------------+
475| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
476+-----------------------+-------------------------+---------------------------------------+
477| Subtraction | ``a - b`` | ``sub(a, b)`` |
478+-----------------------+-------------------------+---------------------------------------+
479| Truth Test | ``obj`` | ``truth(obj)`` |
480+-----------------------+-------------------------+---------------------------------------+
481| Ordering | ``a < b`` | ``lt(a, b)`` |
482+-----------------------+-------------------------+---------------------------------------+
483| Ordering | ``a <= b`` | ``le(a, b)`` |
484+-----------------------+-------------------------+---------------------------------------+
485| Equality | ``a == b`` | ``eq(a, b)`` |
486+-----------------------+-------------------------+---------------------------------------+
487| Difference | ``a != b`` | ``ne(a, b)`` |
488+-----------------------+-------------------------+---------------------------------------+
489| Ordering | ``a >= b`` | ``ge(a, b)`` |
490+-----------------------+-------------------------+---------------------------------------+
491| Ordering | ``a > b`` | ``gt(a, b)`` |
492+-----------------------+-------------------------+---------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000493