blob: 175314ee641cb2c1e082a607001e40014b3c53ef [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
112 .. versionadded:: 2.5
113
114
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000115.. function:: inv(obj)
116 invert(obj)
117 __inv__(obj)
118 __invert__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000120 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123.. function:: lshift(a, b)
124 __lshift__(a, b)
125
126 Return *a* shifted left by *b*.
127
128
129.. function:: mod(a, b)
130 __mod__(a, b)
131
132 Return ``a % b``.
133
134
135.. function:: mul(a, b)
136 __mul__(a, b)
137
138 Return ``a * b``, for *a* and *b* numbers.
139
140
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000141.. function:: neg(obj)
142 __neg__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000144 Return *obj* negated (``-obj``).
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146
147.. function:: or_(a, b)
148 __or__(a, b)
149
150 Return the bitwise or of *a* and *b*.
151
152
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153.. function:: pos(obj)
154 __pos__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000156 Return *obj* positive (``+obj``).
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158
159.. function:: pow(a, b)
160 __pow__(a, b)
161
162 Return ``a ** b``, for *a* and *b* numbers.
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. function:: rshift(a, b)
166 __rshift__(a, b)
167
168 Return *a* shifted right by *b*.
169
170
171.. function:: sub(a, b)
172 __sub__(a, b)
173
174 Return ``a - b``.
175
176
177.. function:: truediv(a, b)
178 __truediv__(a, b)
179
Georg Brandlf6945182008-02-01 11:56:49 +0000180 Return ``a / b`` where 2/3 is .66 rather than 0. This is also known as
181 "true" division.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184.. function:: xor(a, b)
185 __xor__(a, b)
186
187 Return the bitwise exclusive or of *a* and *b*.
188
189
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000190Operations which work with sequences (some of them with mappings too) include:
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192.. function:: concat(a, b)
193 __concat__(a, b)
194
195 Return ``a + b`` for *a* and *b* sequences.
196
197
198.. function:: contains(a, b)
199 __contains__(a, b)
200
201 Return the outcome of the test ``b in a``. Note the reversed operands.
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204.. function:: countOf(a, b)
205
206 Return the number of occurrences of *b* in *a*.
207
208
209.. function:: delitem(a, b)
210 __delitem__(a, b)
211
212 Remove the value of *a* at index *b*.
213
Georg Brandl48310cd2009-01-03 21:18:54 +0000214
Georg Brandl116aa622007-08-15 14:28:22 +0000215.. function:: getitem(a, b)
216 __getitem__(a, b)
217
218 Return the value of *a* at index *b*.
219
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221.. function:: indexOf(a, b)
222
223 Return the index of the first of occurrence of *b* in *a*.
224
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226.. function:: setitem(a, b, c)
227 __setitem__(a, b, c)
228
229 Set the value of *a* at index *b* to *c*.
230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232Many operations have an "in-place" version. The following functions provide a
233more primitive access to in-place operators than the usual syntax does; for
Christian Heimesd8654cf2007-12-02 15:22:16 +0000234example, the :term:`statement` ``x += y`` is equivalent to
235``x = operator.iadd(x, y)``. Another way to put it is to say that
236``z = operator.iadd(x, y)`` is equivalent to the compound statement
237``z = x; z += y``.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239.. function:: iadd(a, b)
240 __iadd__(a, b)
241
242 ``a = iadd(a, b)`` is equivalent to ``a += b``.
243
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245.. function:: iand(a, b)
246 __iand__(a, b)
247
248 ``a = iand(a, b)`` is equivalent to ``a &= b``.
249
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251.. function:: iconcat(a, b)
252 __iconcat__(a, b)
253
254 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandl116aa622007-08-15 14:28:22 +0000257.. function:: ifloordiv(a, b)
258 __ifloordiv__(a, b)
259
260 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
261
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263.. function:: ilshift(a, b)
264 __ilshift__(a, b)
265
Georg Brandl55ac8f02007-09-01 13:51:09 +0000266 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
269.. function:: imod(a, b)
270 __imod__(a, b)
271
272 ``a = imod(a, b)`` is equivalent to ``a %= b``.
273
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275.. function:: imul(a, b)
276 __imul__(a, b)
277
278 ``a = imul(a, b)`` is equivalent to ``a *= b``.
279
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281.. function:: ior(a, b)
282 __ior__(a, b)
283
284 ``a = ior(a, b)`` is equivalent to ``a |= b``.
285
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287.. function:: ipow(a, b)
288 __ipow__(a, b)
289
290 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
291
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Georg Brandl116aa622007-08-15 14:28:22 +0000293.. function:: irshift(a, b)
294 __irshift__(a, b)
295
296 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299.. function:: isub(a, b)
300 __isub__(a, b)
301
302 ``a = isub(a, b)`` is equivalent to ``a -= b``.
303
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305.. function:: itruediv(a, b)
306 __itruediv__(a, b)
307
Georg Brandlf6945182008-02-01 11:56:49 +0000308 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. function:: ixor(a, b)
312 __ixor__(a, b)
313
314 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
315
Georg Brandl116aa622007-08-15 14:28:22 +0000316Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
Christian Heimesfe337bf2008-03-23 21:54:12 +0000317their character equivalents.
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Georg Brandl116aa622007-08-15 14:28:22 +0000319 >>> d = {}
320 >>> keys = range(256)
321 >>> vals = map(chr, keys)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000322 >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324.. XXX: find a better, readable, example
325
326The :mod:`operator` module also defines tools for generalized attribute and item
327lookups. These are useful for making fast field extractors as arguments for
328:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
329expect a function argument.
330
331
332.. function:: attrgetter(attr[, args...])
333
334 Return a callable object that fetches *attr* from its operand. If more than one
335 attribute is requested, returns a tuple of attributes. After,
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000336 ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
337 ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
Georg Brandl116aa622007-08-15 14:28:22 +0000338 b.date)``.
339
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000340 The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
341 the call ``f(b)`` returns ``b.date.month``.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343.. function:: itemgetter(item[, args...])
344
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000345 Return a callable object that fetches *item* from its operand using the
346 operand's :meth:`__getitem__` method. If multiple items are specified,
347 returns a tuple of lookup values. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000349 def itemgetter(*items):
350 if len(items) == 1:
351 item = items[0]
352 def g(obj):
353 return obj[item]
354 else:
355 def g(obj):
356 return tuple(obj[item] for item in items)
357 return g
Georg Brandl48310cd2009-01-03 21:18:54 +0000358
359 The items can be any type accepted by the operand's :meth:`__getitem__`
360 method. Dictionaries accept any hashable value. Lists, tuples, and
Christian Heimesfe337bf2008-03-23 21:54:12 +0000361 strings accept an index or a slice:
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Christian Heimesfe337bf2008-03-23 21:54:12 +0000363 >>> itemgetter(1)('ABCDEFG')
364 'B'
365 >>> itemgetter(1,3,5)('ABCDEFG')
366 ('B', 'D', 'F')
367 >>> itemgetter(slice(2,None))('ABCDEFG')
368 'CDEFG'
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000370
371 Example of using :func:`itemgetter` to retrieve specific fields from a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000372 tuple record:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000373
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000374 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
375 >>> getcount = itemgetter(1)
376 >>> map(getcount, inventory)
377 [3, 2, 5, 1]
378 >>> sorted(inventory, key=getcount)
379 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000382.. function:: methodcaller(name[, args...])
383
384 Return a callable object that calls the method *name* on its operand. If
385 additional arguments and/or keyword arguments are given, they will be given
386 to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
387 returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
388 call ``f(b)`` returns ``b.name('foo', bar=1)``.
389
390
Georg Brandl116aa622007-08-15 14:28:22 +0000391.. _operator-map:
392
393Mapping Operators to Functions
394------------------------------
395
396This table shows how abstract operations correspond to operator symbols in the
397Python syntax and the functions in the :mod:`operator` module.
398
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000399+-----------------------+-------------------------+---------------------------------------+
400| Operation | Syntax | Function |
401+=======================+=========================+=======================================+
402| Addition | ``a + b`` | ``add(a, b)`` |
403+-----------------------+-------------------------+---------------------------------------+
404| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
405+-----------------------+-------------------------+---------------------------------------+
406| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
407+-----------------------+-------------------------+---------------------------------------+
408| Division | ``a / b`` | ``div(a, b)`` |
409+-----------------------+-------------------------+---------------------------------------+
410| Division | ``a // b`` | ``floordiv(a, b)`` |
411+-----------------------+-------------------------+---------------------------------------+
412| Bitwise And | ``a & b`` | ``and_(a, b)`` |
413+-----------------------+-------------------------+---------------------------------------+
414| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
415+-----------------------+-------------------------+---------------------------------------+
416| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
417+-----------------------+-------------------------+---------------------------------------+
418| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
419+-----------------------+-------------------------+---------------------------------------+
420| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
421+-----------------------+-------------------------+---------------------------------------+
422| Identity | ``a is b`` | ``is_(a, b)`` |
423+-----------------------+-------------------------+---------------------------------------+
424| Identity | ``a is not b`` | ``is_not(a, b)`` |
425+-----------------------+-------------------------+---------------------------------------+
426| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
427+-----------------------+-------------------------+---------------------------------------+
428| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
429+-----------------------+-------------------------+---------------------------------------+
430| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
431+-----------------------+-------------------------+---------------------------------------+
432| Left Shift | ``a << b`` | ``lshift(a, b)`` |
433+-----------------------+-------------------------+---------------------------------------+
434| Modulo | ``a % b`` | ``mod(a, b)`` |
435+-----------------------+-------------------------+---------------------------------------+
436| Multiplication | ``a * b`` | ``mul(a, b)`` |
437+-----------------------+-------------------------+---------------------------------------+
438| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
439+-----------------------+-------------------------+---------------------------------------+
440| Negation (Logical) | ``not a`` | ``not_(a)`` |
441+-----------------------+-------------------------+---------------------------------------+
442| Positive | ``+ a`` | ``pos(a)`` |
443+-----------------------+-------------------------+---------------------------------------+
444| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
445+-----------------------+-------------------------+---------------------------------------+
446| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
447+-----------------------+-------------------------+---------------------------------------+
448| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
449+-----------------------+-------------------------+---------------------------------------+
450| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
451+-----------------------+-------------------------+---------------------------------------+
452| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
453+-----------------------+-------------------------+---------------------------------------+
454| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
455+-----------------------+-------------------------+---------------------------------------+
456| Subtraction | ``a - b`` | ``sub(a, b)`` |
457+-----------------------+-------------------------+---------------------------------------+
458| Truth Test | ``obj`` | ``truth(obj)`` |
459+-----------------------+-------------------------+---------------------------------------+
460| Ordering | ``a < b`` | ``lt(a, b)`` |
461+-----------------------+-------------------------+---------------------------------------+
462| Ordering | ``a <= b`` | ``le(a, b)`` |
463+-----------------------+-------------------------+---------------------------------------+
464| Equality | ``a == b`` | ``eq(a, b)`` |
465+-----------------------+-------------------------+---------------------------------------+
466| Difference | ``a != b`` | ``ne(a, b)`` |
467+-----------------------+-------------------------+---------------------------------------+
468| Ordering | ``a >= b`` | ``ge(a, b)`` |
469+-----------------------+-------------------------+---------------------------------------+
470| Ordering | ``a > b`` | ``gt(a, b)`` |
471+-----------------------+-------------------------+---------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000472