blob: 40acc6b7b4263af7e639dda06c109c044ef59455 [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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000050.. function:: not_(obj)
51 __not__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000052
Thomas Wouters1b7f8912007-09-19 03:06:30 +000053 Return the outcome of :keyword:`not` *obj*. (Note that there is no
Georg Brandl116aa622007-08-15 14:28:22 +000054 :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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000059.. function:: truth(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000060
Thomas Wouters1b7f8912007-09-19 03:06:30 +000061 Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
Georg Brandl116aa622007-08-15 14:28:22 +000062 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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000078.. function:: abs(obj)
79 __abs__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +000080
Thomas Wouters1b7f8912007-09-19 03:06:30 +000081 Return the absolute value of *obj*.
Georg Brandl116aa622007-08-15 14:28:22 +000082
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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000109.. function:: inv(obj)
110 invert(obj)
111 __inv__(obj)
112 __invert__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000114 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000135.. function:: neg(obj)
136 __neg__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000138 Return *obj* negated.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140
141.. function:: or_(a, b)
142 __or__(a, b)
143
144 Return the bitwise or of *a* and *b*.
145
146
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000147.. function:: pos(obj)
148 __pos__(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000150 Return *obj* positive.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000376 >>> obj = C()
377 >>> operator.isMappingType(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000378 True
379
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382 Python 3 is expected to introduce abstract base classes for
383 collection types, so it should be possible to write, for example,
384 ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj,
385 collections.Sequence)``.
386
387.. function:: isCallable(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389 .. deprecated:: 2.0
390 Use the :func:`callable` built-in function instead.
391
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000392 Returns true if the object *obj* can be called like a function, otherwise it
Georg Brandl116aa622007-08-15 14:28:22 +0000393 returns false. True is returned for functions, bound and unbound methods, class
394 objects, and instance objects which support the :meth:`__call__` method.
395
396
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000397.. function:: isMappingType(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399 Returns true if the object *obj* supports the mapping interface. This is true for
Georg Brandl116aa622007-08-15 14:28:22 +0000400 dictionaries and all instance objects defining :meth:`__getitem__`.
401
402 .. warning::
403
404 There is no reliable way to test if an instance supports the complete mapping
405 protocol since the interface itself is ill-defined. This makes this test less
406 useful than it otherwise might be.
407
408
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409.. function:: isNumberType(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411 Returns true if the object *obj* represents a number. This is true for all
Georg Brandl116aa622007-08-15 14:28:22 +0000412 numeric types implemented in C.
413
414 .. warning::
415
416 There is no reliable way to test if an instance supports the complete numeric
417 interface since the interface itself is ill-defined. This makes this test less
418 useful than it otherwise might be.
419
420
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421.. function:: isSequenceType(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000423 Returns true if the object *obj* supports the sequence protocol. This returns true
Georg Brandl116aa622007-08-15 14:28:22 +0000424 for all objects which define sequence methods in C, and for all instance objects
425 defining :meth:`__getitem__`.
426
427 .. warning::
428
429 There is no reliable way to test if an instance supports the complete sequence
430 interface since the interface itself is ill-defined. This makes this test less
431 useful than it otherwise might be.
432
433Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
434their character equivalents. ::
435
436 >>> import operator
437 >>> d = {}
438 >>> keys = range(256)
439 >>> vals = map(chr, keys)
440 >>> map(operator.setitem, [d]*len(keys), keys, vals)
441
442.. XXX: find a better, readable, example
443
444The :mod:`operator` module also defines tools for generalized attribute and item
445lookups. These are useful for making fast field extractors as arguments for
446:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
447expect a function argument.
448
449
450.. function:: attrgetter(attr[, args...])
451
452 Return a callable object that fetches *attr* from its operand. If more than one
453 attribute is requested, returns a tuple of attributes. After,
454 ``f=attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
455 ``f=attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
456 b.date)``.
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459.. function:: itemgetter(item[, args...])
460
461 Return a callable object that fetches *item* from its operand. If more than one
462 item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the
463 call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call
464 ``f(b)`` returns ``(b[2], b[5], b[3])``.
465
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467Examples::
468
469 >>> from operator import itemgetter
470 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
471 >>> getcount = itemgetter(1)
472 >>> map(getcount, inventory)
473 [3, 2, 5, 1]
474 >>> sorted(inventory, key=getcount)
475 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
476
477
478.. _operator-map:
479
480Mapping Operators to Functions
481------------------------------
482
483This table shows how abstract operations correspond to operator symbols in the
484Python syntax and the functions in the :mod:`operator` module.
485
486+-----------------------+-------------------------+---------------------------------+
487| Operation | Syntax | Function |
488+=======================+=========================+=================================+
489| Addition | ``a + b`` | ``add(a, b)`` |
490+-----------------------+-------------------------+---------------------------------+
491| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
492+-----------------------+-------------------------+---------------------------------+
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000494+-----------------------+-------------------------+---------------------------------+
495| Division | ``a / b`` | ``div(a, b)`` (without |
496| | | ``__future__.division``) |
497+-----------------------+-------------------------+---------------------------------+
498| Division | ``a / b`` | ``truediv(a, b)`` (with |
499| | | ``__future__.division``) |
500+-----------------------+-------------------------+---------------------------------+
501| Division | ``a // b`` | ``floordiv(a, b)`` |
502+-----------------------+-------------------------+---------------------------------+
503| Bitwise And | ``a & b`` | ``and_(a, b)`` |
504+-----------------------+-------------------------+---------------------------------+
505| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
506+-----------------------+-------------------------+---------------------------------+
507| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
508+-----------------------+-------------------------+---------------------------------+
509| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
510+-----------------------+-------------------------+---------------------------------+
511| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
512+-----------------------+-------------------------+---------------------------------+
513| Identity | ``a is b`` | ``is_(a, b)`` |
514+-----------------------+-------------------------+---------------------------------+
515| Identity | ``a is not b`` | ``is_not(a, b)`` |
516+-----------------------+-------------------------+---------------------------------+
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000518+-----------------------+-------------------------+---------------------------------+
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000520+-----------------------+-------------------------+---------------------------------+
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000522+-----------------------+-------------------------+---------------------------------+
523| Left Shift | ``a << b`` | ``lshift(a, b)`` |
524+-----------------------+-------------------------+---------------------------------+
525| Modulo | ``a % b`` | ``mod(a, b)`` |
526+-----------------------+-------------------------+---------------------------------+
527| Multiplication | ``a * b`` | ``mul(a, b)`` |
528+-----------------------+-------------------------+---------------------------------+
529| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
530+-----------------------+-------------------------+---------------------------------+
531| Negation (Logical) | ``not a`` | ``not_(a)`` |
532+-----------------------+-------------------------+---------------------------------+
533| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
534+-----------------------+-------------------------+---------------------------------+
535| Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` |
536+-----------------------+-------------------------+---------------------------------+
537| Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
538+-----------------------+-------------------------+---------------------------------+
539| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
540+-----------------------+-------------------------+---------------------------------+
541| Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
542+-----------------------+-------------------------+---------------------------------+
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000544+-----------------------+-------------------------+---------------------------------+
545| Subtraction | ``a - b`` | ``sub(a, b)`` |
546+-----------------------+-------------------------+---------------------------------+
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547| Truth Test | ``obj`` | ``truth(obj)`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000548+-----------------------+-------------------------+---------------------------------+
549| Ordering | ``a < b`` | ``lt(a, b)`` |
550+-----------------------+-------------------------+---------------------------------+
551| Ordering | ``a <= b`` | ``le(a, b)`` |
552+-----------------------+-------------------------+---------------------------------+
553| Equality | ``a == b`` | ``eq(a, b)`` |
554+-----------------------+-------------------------+---------------------------------+
555| Difference | ``a != b`` | ``ne(a, b)`` |
556+-----------------------+-------------------------+---------------------------------+
557| Ordering | ``a >= b`` | ``ge(a, b)`` |
558+-----------------------+-------------------------+---------------------------------+
559| Ordering | ``a > b`` | ``gt(a, b)`` |
560+-----------------------+-------------------------+---------------------------------+
561