blob: f3969786df9b727049ff70e59b45c33d48ef92ff [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
9
10The :mod:`operator` module exports a set of functions implemented in C
11corresponding to the intrinsic operators of Python. For example,
12``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function
13names are those used for special class methods; variants without leading and
14trailing ``__`` are also provided for convenience.
15
16The functions fall into categories that perform object comparisons, logical
17operations, mathematical operations, sequence operations, and abstract type
18tests.
19
20The object comparison functions are useful for all objects, and are named after
21the rich comparison operators they support:
22
23
24.. function:: lt(a, b)
25 le(a, b)
26 eq(a, b)
27 ne(a, b)
28 ge(a, b)
29 gt(a, b)
30 __lt__(a, b)
31 __le__(a, b)
32 __eq__(a, b)
33 __ne__(a, b)
34 __ge__(a, b)
35 __gt__(a, b)
36
37 Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
38 equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
39 b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
40 ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
41 >= b``. Note that unlike the built-in :func:`cmp`, these functions can
42 return any value, which may or may not be interpretable as a Boolean value.
43 See :ref:`comparisons` for more information about rich comparisons.
44
Georg Brandl116aa622007-08-15 14:28:22 +000045
46The logical operations are also generally applicable to all objects, and support
47truth tests, identity tests, and boolean operations:
48
49
50.. function:: not_(o)
51 __not__(o)
52
53 Return the outcome of :keyword:`not` *o*. (Note that there is no
54 :meth:`__not__` method for object instances; only the interpreter core defines
55 this operation. The result is affected by the :meth:`__bool__` and
56 :meth:`__len__` methods.)
57
58
59.. function:: truth(o)
60
61 Return :const:`True` if *o* is true, and :const:`False` otherwise. This is
62 equivalent to using the :class:`bool` constructor.
63
64
65.. function:: is_(a, b)
66
67 Return ``a is b``. Tests object identity.
68
Georg Brandl116aa622007-08-15 14:28:22 +000069
70.. function:: is_not(a, b)
71
72 Return ``a is not b``. Tests object identity.
73
Georg Brandl116aa622007-08-15 14:28:22 +000074
75The mathematical and bitwise operations are the most numerous:
76
77
78.. function:: abs(o)
79 __abs__(o)
80
81 Return the absolute value of *o*.
82
83
84.. function:: add(a, b)
85 __add__(a, b)
86
87 Return ``a + b``, for *a* and *b* numbers.
88
89
90.. function:: and_(a, b)
91 __and__(a, b)
92
93 Return the bitwise and of *a* and *b*.
94
95
96.. function:: div(a, b)
97 __div__(a, b)
98
99 Return ``a / b`` when ``__future__.division`` is not in effect. This is
100 also known as "classic" division.
101
102
103.. function:: floordiv(a, b)
104 __floordiv__(a, b)
105
106 Return ``a // b``.
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109.. function:: inv(o)
110 invert(o)
111 __inv__(o)
112 __invert__(o)
113
114 Return the bitwise inverse of the number *o*. This is equivalent to ``~o``.
115
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117.. function:: lshift(a, b)
118 __lshift__(a, b)
119
120 Return *a* shifted left by *b*.
121
122
123.. function:: mod(a, b)
124 __mod__(a, b)
125
126 Return ``a % b``.
127
128
129.. function:: mul(a, b)
130 __mul__(a, b)
131
132 Return ``a * b``, for *a* and *b* numbers.
133
134
135.. function:: neg(o)
136 __neg__(o)
137
138 Return *o* negated.
139
140
141.. function:: or_(a, b)
142 __or__(a, b)
143
144 Return the bitwise or of *a* and *b*.
145
146
147.. function:: pos(o)
148 __pos__(o)
149
150 Return *o* positive.
151
152
153.. function:: pow(a, b)
154 __pow__(a, b)
155
156 Return ``a ** b``, for *a* and *b* numbers.
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159.. function:: rshift(a, b)
160 __rshift__(a, b)
161
162 Return *a* shifted right by *b*.
163
164
165.. function:: sub(a, b)
166 __sub__(a, b)
167
168 Return ``a - b``.
169
170
171.. function:: truediv(a, b)
172 __truediv__(a, b)
173
174 Return ``a / b`` when ``__future__.division`` is in effect. This is also
175 known as "true" division.
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. function:: xor(a, b)
179 __xor__(a, b)
180
181 Return the bitwise exclusive or of *a* and *b*.
182
183
184.. function:: index(a)
185 __index__(a)
186
187 Return *a* converted to an integer. Equivalent to ``a.__index__()``.
188
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190Operations which work with sequences include:
191
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
214
215.. function:: delslice(a, b, c)
216 __delslice__(a, b, c)
217
218 Delete the slice of *a* from index *b* to index *c-1*.
219
220
221.. function:: getitem(a, b)
222 __getitem__(a, b)
223
224 Return the value of *a* at index *b*.
225
226
227.. function:: getslice(a, b, c)
228 __getslice__(a, b, c)
229
230 Return the slice of *a* from index *b* to index *c-1*.
231
232
233.. function:: indexOf(a, b)
234
235 Return the index of the first of occurrence of *b* in *a*.
236
237
238.. function:: repeat(a, b)
239 __repeat__(a, b)
240
241 Return ``a * b`` where *a* is a sequence and *b* is an integer.
242
243
244.. function:: sequenceIncludes(...)
245
246 .. deprecated:: 2.0
247 Use :func:`contains` instead.
248
249 Alias for :func:`contains`.
250
251
252.. function:: setitem(a, b, c)
253 __setitem__(a, b, c)
254
255 Set the value of *a* at index *b* to *c*.
256
257
258.. function:: setslice(a, b, c, v)
259 __setslice__(a, b, c, v)
260
261 Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
262
263Many operations have an "in-place" version. The following functions provide a
264more primitive access to in-place operators than the usual syntax does; for
265example, the statement ``x += y`` is equivalent to ``x = operator.iadd(x, y)``.
266Another way to put it is to say that ``z = operator.iadd(x, y)`` is equivalent
267to the compound statement ``z = x; z += y``.
268
269
270.. function:: iadd(a, b)
271 __iadd__(a, b)
272
273 ``a = iadd(a, b)`` is equivalent to ``a += b``.
274
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276.. function:: iand(a, b)
277 __iand__(a, b)
278
279 ``a = iand(a, b)`` is equivalent to ``a &= b``.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282.. function:: iconcat(a, b)
283 __iconcat__(a, b)
284
285 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
286
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288.. function:: idiv(a, b)
289 __idiv__(a, b)
290
291 ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
292 not in effect.
293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295.. function:: ifloordiv(a, b)
296 __ifloordiv__(a, b)
297
298 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
299
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301.. function:: ilshift(a, b)
302 __ilshift__(a, b)
303
Georg Brandl55ac8f02007-09-01 13:51:09 +0000304 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306
307.. function:: imod(a, b)
308 __imod__(a, b)
309
310 ``a = imod(a, b)`` is equivalent to ``a %= b``.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313.. function:: imul(a, b)
314 __imul__(a, b)
315
316 ``a = imul(a, b)`` is equivalent to ``a *= b``.
317
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319.. function:: ior(a, b)
320 __ior__(a, b)
321
322 ``a = ior(a, b)`` is equivalent to ``a |= b``.
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324
325.. function:: ipow(a, b)
326 __ipow__(a, b)
327
328 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331.. function:: irepeat(a, b)
332 __irepeat__(a, b)
333
334 ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
335 *b* is an integer.
336
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338.. function:: irshift(a, b)
339 __irshift__(a, b)
340
341 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
342
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344.. function:: isub(a, b)
345 __isub__(a, b)
346
347 ``a = isub(a, b)`` is equivalent to ``a -= b``.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350.. function:: itruediv(a, b)
351 __itruediv__(a, b)
352
353 ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
354 is in effect.
355
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357.. function:: ixor(a, b)
358 __ixor__(a, b)
359
360 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363The :mod:`operator` module also defines a few predicates to test the type of
364objects.
365
366.. note::
367
368 Be careful not to misinterpret the results of these functions; only
369 :func:`isCallable` has any measure of reliability with instance objects.
370 For example::
371
372 >>> class C:
373 ... pass
374 ...
375 >>> import operator
376 >>> o = C()
377 >>> operator.isMappingType(o)
378 True
379
380
381.. function:: isCallable(o)
382
383 .. deprecated:: 2.0
384 Use the :func:`callable` built-in function instead.
385
386 Returns true if the object *o* can be called like a function, otherwise it
387 returns false. True is returned for functions, bound and unbound methods, class
388 objects, and instance objects which support the :meth:`__call__` method.
389
390
391.. function:: isMappingType(o)
392
393 Returns true if the object *o* supports the mapping interface. This is true for
394 dictionaries and all instance objects defining :meth:`__getitem__`.
395
396 .. warning::
397
398 There is no reliable way to test if an instance supports the complete mapping
399 protocol since the interface itself is ill-defined. This makes this test less
400 useful than it otherwise might be.
401
402
403.. function:: isNumberType(o)
404
405 Returns true if the object *o* represents a number. This is true for all
406 numeric types implemented in C.
407
408 .. warning::
409
410 There is no reliable way to test if an instance supports the complete numeric
411 interface since the interface itself is ill-defined. This makes this test less
412 useful than it otherwise might be.
413
414
415.. function:: isSequenceType(o)
416
417 Returns true if the object *o* supports the sequence protocol. This returns true
418 for all objects which define sequence methods in C, and for all instance objects
419 defining :meth:`__getitem__`.
420
421 .. warning::
422
423 There is no reliable way to test if an instance supports the complete sequence
424 interface since the interface itself is ill-defined. This makes this test less
425 useful than it otherwise might be.
426
427Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
428their character equivalents. ::
429
430 >>> import operator
431 >>> d = {}
432 >>> keys = range(256)
433 >>> vals = map(chr, keys)
434 >>> map(operator.setitem, [d]*len(keys), keys, vals)
435
436.. XXX: find a better, readable, example
437
438The :mod:`operator` module also defines tools for generalized attribute and item
439lookups. These are useful for making fast field extractors as arguments for
440:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
441expect a function argument.
442
443
444.. function:: attrgetter(attr[, args...])
445
446 Return a callable object that fetches *attr* from its operand. If more than one
447 attribute is requested, returns a tuple of attributes. After,
448 ``f=attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
449 ``f=attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
450 b.date)``.
451
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453.. function:: itemgetter(item[, args...])
454
455 Return a callable object that fetches *item* from its operand. If more than one
456 item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the
457 call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call
458 ``f(b)`` returns ``(b[2], b[5], b[3])``.
459
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461Examples::
462
463 >>> from operator import itemgetter
464 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
465 >>> getcount = itemgetter(1)
466 >>> map(getcount, inventory)
467 [3, 2, 5, 1]
468 >>> sorted(inventory, key=getcount)
469 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
470
471
472.. _operator-map:
473
474Mapping Operators to Functions
475------------------------------
476
477This table shows how abstract operations correspond to operator symbols in the
478Python syntax and the functions in the :mod:`operator` module.
479
480+-----------------------+-------------------------+---------------------------------+
481| Operation | Syntax | Function |
482+=======================+=========================+=================================+
483| Addition | ``a + b`` | ``add(a, b)`` |
484+-----------------------+-------------------------+---------------------------------+
485| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
486+-----------------------+-------------------------+---------------------------------+
487| Containment Test | ``o in seq`` | ``contains(seq, o)`` |
488+-----------------------+-------------------------+---------------------------------+
489| Division | ``a / b`` | ``div(a, b)`` (without |
490| | | ``__future__.division``) |
491+-----------------------+-------------------------+---------------------------------+
492| Division | ``a / b`` | ``truediv(a, b)`` (with |
493| | | ``__future__.division``) |
494+-----------------------+-------------------------+---------------------------------+
495| Division | ``a // b`` | ``floordiv(a, b)`` |
496+-----------------------+-------------------------+---------------------------------+
497| Bitwise And | ``a & b`` | ``and_(a, b)`` |
498+-----------------------+-------------------------+---------------------------------+
499| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
500+-----------------------+-------------------------+---------------------------------+
501| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
502+-----------------------+-------------------------+---------------------------------+
503| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
504+-----------------------+-------------------------+---------------------------------+
505| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
506+-----------------------+-------------------------+---------------------------------+
507| Identity | ``a is b`` | ``is_(a, b)`` |
508+-----------------------+-------------------------+---------------------------------+
509| Identity | ``a is not b`` | ``is_not(a, b)`` |
510+-----------------------+-------------------------+---------------------------------+
511| Indexed Assignment | ``o[k] = v`` | ``setitem(o, k, v)`` |
512+-----------------------+-------------------------+---------------------------------+
513| Indexed Deletion | ``del o[k]`` | ``delitem(o, k)`` |
514+-----------------------+-------------------------+---------------------------------+
515| Indexing | ``o[k]`` | ``getitem(o, k)`` |
516+-----------------------+-------------------------+---------------------------------+
517| Left Shift | ``a << b`` | ``lshift(a, b)`` |
518+-----------------------+-------------------------+---------------------------------+
519| Modulo | ``a % b`` | ``mod(a, b)`` |
520+-----------------------+-------------------------+---------------------------------+
521| Multiplication | ``a * b`` | ``mul(a, b)`` |
522+-----------------------+-------------------------+---------------------------------+
523| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
524+-----------------------+-------------------------+---------------------------------+
525| Negation (Logical) | ``not a`` | ``not_(a)`` |
526+-----------------------+-------------------------+---------------------------------+
527| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
528+-----------------------+-------------------------+---------------------------------+
529| Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` |
530+-----------------------+-------------------------+---------------------------------+
531| Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
532+-----------------------+-------------------------+---------------------------------+
533| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
534+-----------------------+-------------------------+---------------------------------+
535| Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
536+-----------------------+-------------------------+---------------------------------+
537| String Formatting | ``s % o`` | ``mod(s, o)`` |
538+-----------------------+-------------------------+---------------------------------+
539| Subtraction | ``a - b`` | ``sub(a, b)`` |
540+-----------------------+-------------------------+---------------------------------+
541| Truth Test | ``o`` | ``truth(o)`` |
542+-----------------------+-------------------------+---------------------------------+
543| Ordering | ``a < b`` | ``lt(a, b)`` |
544+-----------------------+-------------------------+---------------------------------+
545| Ordering | ``a <= b`` | ``le(a, b)`` |
546+-----------------------+-------------------------+---------------------------------+
547| Equality | ``a == b`` | ``eq(a, b)`` |
548+-----------------------+-------------------------+---------------------------------+
549| Difference | ``a != b`` | ``ne(a, b)`` |
550+-----------------------+-------------------------+---------------------------------+
551| Ordering | ``a >= b`` | ``ge(a, b)`` |
552+-----------------------+-------------------------+---------------------------------+
553| Ordering | ``a > b`` | ``gt(a, b)`` |
554+-----------------------+-------------------------+---------------------------------+
555