blob: ea4d328ffe52dbd1d7668aa7f62087d53b920637 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
45 .. versionadded:: 2.2
46
47The logical operations are also generally applicable to all objects, and support
48truth tests, identity tests, and boolean operations:
49
50
Mark Summerfieldddca9f02007-09-13 14:54:30 +000051.. function:: not_(obj)
52 __not__(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
Mark Summerfieldddca9f02007-09-13 14:54:30 +000054 Return the outcome of :keyword:`not` *obj*. (Note that there is no
Georg Brandl8ec7f652007-08-15 14:28:01 +000055 :meth:`__not__` method for object instances; only the interpreter core defines
56 this operation. The result is affected by the :meth:`__nonzero__` and
57 :meth:`__len__` methods.)
58
59
Mark Summerfieldddca9f02007-09-13 14:54:30 +000060.. function:: truth(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +000061
Mark Summerfieldddca9f02007-09-13 14:54:30 +000062 Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
Georg Brandl8ec7f652007-08-15 14:28:01 +000063 equivalent to using the :class:`bool` constructor.
64
65
66.. function:: is_(a, b)
67
68 Return ``a is b``. Tests object identity.
69
70 .. versionadded:: 2.3
71
72
73.. function:: is_not(a, b)
74
75 Return ``a is not b``. Tests object identity.
76
77 .. versionadded:: 2.3
78
79The mathematical and bitwise operations are the most numerous:
80
81
Mark Summerfieldddca9f02007-09-13 14:54:30 +000082.. function:: abs(obj)
83 __abs__(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +000084
Mark Summerfieldddca9f02007-09-13 14:54:30 +000085 Return the absolute value of *obj*.
Georg Brandl8ec7f652007-08-15 14:28:01 +000086
87
88.. function:: add(a, b)
89 __add__(a, b)
90
91 Return ``a + b``, for *a* and *b* numbers.
92
93
94.. function:: and_(a, b)
95 __and__(a, b)
96
97 Return the bitwise and of *a* and *b*.
98
99
100.. function:: div(a, b)
101 __div__(a, b)
102
103 Return ``a / b`` when ``__future__.division`` is not in effect. This is
104 also known as "classic" division.
105
106
107.. function:: floordiv(a, b)
108 __floordiv__(a, b)
109
110 Return ``a // b``.
111
112 .. versionadded:: 2.2
113
114
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000115.. function:: inv(obj)
116 invert(obj)
117 __inv__(obj)
118 __invert__(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000120 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121
122 .. versionadded:: 2.0
123 The names :func:`invert` and :func:`__invert__`.
124
125
126.. function:: lshift(a, b)
127 __lshift__(a, b)
128
129 Return *a* shifted left by *b*.
130
131
132.. function:: mod(a, b)
133 __mod__(a, b)
134
135 Return ``a % b``.
136
137
138.. function:: mul(a, b)
139 __mul__(a, b)
140
141 Return ``a * b``, for *a* and *b* numbers.
142
143
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000144.. function:: neg(obj)
145 __neg__(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000147 Return *obj* negated.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000148
149
150.. function:: or_(a, b)
151 __or__(a, b)
152
153 Return the bitwise or of *a* and *b*.
154
155
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000156.. function:: pos(obj)
157 __pos__(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000159 Return *obj* positive.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
161
162.. function:: pow(a, b)
163 __pow__(a, b)
164
165 Return ``a ** b``, for *a* and *b* numbers.
166
167 .. versionadded:: 2.3
168
169
170.. function:: rshift(a, b)
171 __rshift__(a, b)
172
173 Return *a* shifted right by *b*.
174
175
176.. function:: sub(a, b)
177 __sub__(a, b)
178
179 Return ``a - b``.
180
181
182.. function:: truediv(a, b)
183 __truediv__(a, b)
184
185 Return ``a / b`` when ``__future__.division`` is in effect. This is also
186 known as "true" division.
187
188 .. versionadded:: 2.2
189
190
191.. function:: xor(a, b)
192 __xor__(a, b)
193
194 Return the bitwise exclusive or of *a* and *b*.
195
196
197.. function:: index(a)
198 __index__(a)
199
200 Return *a* converted to an integer. Equivalent to ``a.__index__()``.
201
202 .. versionadded:: 2.5
203
204
205Operations which work with sequences include:
206
207.. function:: concat(a, b)
208 __concat__(a, b)
209
210 Return ``a + b`` for *a* and *b* sequences.
211
212
213.. function:: contains(a, b)
214 __contains__(a, b)
215
216 Return the outcome of the test ``b in a``. Note the reversed operands.
217
218 .. versionadded:: 2.0
219 The name :func:`__contains__`.
220
221
222.. function:: countOf(a, b)
223
224 Return the number of occurrences of *b* in *a*.
225
226
227.. function:: delitem(a, b)
228 __delitem__(a, b)
229
230 Remove the value of *a* at index *b*.
231
232
233.. function:: delslice(a, b, c)
234 __delslice__(a, b, c)
235
236 Delete the slice of *a* from index *b* to index *c-1*.
237
238
239.. function:: getitem(a, b)
240 __getitem__(a, b)
241
242 Return the value of *a* at index *b*.
243
244
245.. function:: getslice(a, b, c)
246 __getslice__(a, b, c)
247
248 Return the slice of *a* from index *b* to index *c-1*.
249
250
251.. function:: indexOf(a, b)
252
253 Return the index of the first of occurrence of *b* in *a*.
254
255
256.. function:: repeat(a, b)
257 __repeat__(a, b)
258
259 Return ``a * b`` where *a* is a sequence and *b* is an integer.
260
261
262.. function:: sequenceIncludes(...)
263
264 .. deprecated:: 2.0
265 Use :func:`contains` instead.
266
267 Alias for :func:`contains`.
268
269
270.. function:: setitem(a, b, c)
271 __setitem__(a, b, c)
272
273 Set the value of *a* at index *b* to *c*.
274
275
276.. function:: setslice(a, b, c, v)
277 __setslice__(a, b, c, v)
278
279 Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
280
281Many operations have an "in-place" version. The following functions provide a
282more primitive access to in-place operators than the usual syntax does; for
Georg Brandl584265b2007-12-02 14:58:50 +0000283example, the :term:`statement` ``x += y`` is equivalent to
284``x = operator.iadd(x, y)``. Another way to put it is to say that
285``z = operator.iadd(x, y)`` is equivalent to the compound statement
286``z = x; z += y``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
288.. function:: iadd(a, b)
289 __iadd__(a, b)
290
291 ``a = iadd(a, b)`` is equivalent to ``a += b``.
292
293 .. versionadded:: 2.5
294
295
296.. function:: iand(a, b)
297 __iand__(a, b)
298
299 ``a = iand(a, b)`` is equivalent to ``a &= b``.
300
301 .. versionadded:: 2.5
302
303
304.. function:: iconcat(a, b)
305 __iconcat__(a, b)
306
307 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
308
309 .. versionadded:: 2.5
310
311
312.. function:: idiv(a, b)
313 __idiv__(a, b)
314
315 ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
316 not in effect.
317
318 .. versionadded:: 2.5
319
320
321.. function:: ifloordiv(a, b)
322 __ifloordiv__(a, b)
323
324 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
325
326 .. versionadded:: 2.5
327
328
329.. function:: ilshift(a, b)
330 __ilshift__(a, b)
331
332 ``a = ilshift(a, b)`` is equivalent to ``a <``\ ``<= b``.
333
334 .. versionadded:: 2.5
335
336
337.. function:: imod(a, b)
338 __imod__(a, b)
339
340 ``a = imod(a, b)`` is equivalent to ``a %= b``.
341
342 .. versionadded:: 2.5
343
344
345.. function:: imul(a, b)
346 __imul__(a, b)
347
348 ``a = imul(a, b)`` is equivalent to ``a *= b``.
349
350 .. versionadded:: 2.5
351
352
353.. function:: ior(a, b)
354 __ior__(a, b)
355
356 ``a = ior(a, b)`` is equivalent to ``a |= b``.
357
358 .. versionadded:: 2.5
359
360
361.. function:: ipow(a, b)
362 __ipow__(a, b)
363
364 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
365
366 .. versionadded:: 2.5
367
368
369.. function:: irepeat(a, b)
370 __irepeat__(a, b)
371
372 ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
373 *b* is an integer.
374
375 .. versionadded:: 2.5
376
377
378.. function:: irshift(a, b)
379 __irshift__(a, b)
380
381 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
382
383 .. versionadded:: 2.5
384
385
386.. function:: isub(a, b)
387 __isub__(a, b)
388
389 ``a = isub(a, b)`` is equivalent to ``a -= b``.
390
391 .. versionadded:: 2.5
392
393
394.. function:: itruediv(a, b)
395 __itruediv__(a, b)
396
397 ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
398 is in effect.
399
400 .. versionadded:: 2.5
401
402
403.. function:: ixor(a, b)
404 __ixor__(a, b)
405
406 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
407
408 .. versionadded:: 2.5
409
410
411The :mod:`operator` module also defines a few predicates to test the type of
412objects.
413
414.. note::
415
416 Be careful not to misinterpret the results of these functions; only
417 :func:`isCallable` has any measure of reliability with instance objects.
418 For example::
419
420 >>> class C:
421 ... pass
422 ...
423 >>> import operator
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000424 >>> obj = C()
425 >>> operator.isMappingType(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426 True
427
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000428.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000430 Python 3 is expected to introduce abstract base classes for
431 collection types, so it should be possible to write, for example,
432 ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj,
433 collections.Sequence)``.
434
435.. function:: isCallable(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000436
437 .. deprecated:: 2.0
438 Use the :func:`callable` built-in function instead.
439
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000440 Returns true if the object *obj* can be called like a function, otherwise it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441 returns false. True is returned for functions, bound and unbound methods, class
442 objects, and instance objects which support the :meth:`__call__` method.
443
444
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000445.. function:: isMappingType(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000446
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000447 Returns true if the object *obj* supports the mapping interface. This is true for
Georg Brandl8ec7f652007-08-15 14:28:01 +0000448 dictionaries and all instance objects defining :meth:`__getitem__`.
449
450 .. warning::
451
452 There is no reliable way to test if an instance supports the complete mapping
453 protocol since the interface itself is ill-defined. This makes this test less
454 useful than it otherwise might be.
455
456
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000457.. function:: isNumberType(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000458
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000459 Returns true if the object *obj* represents a number. This is true for all
Georg Brandl8ec7f652007-08-15 14:28:01 +0000460 numeric types implemented in C.
461
462 .. warning::
463
464 There is no reliable way to test if an instance supports the complete numeric
465 interface since the interface itself is ill-defined. This makes this test less
466 useful than it otherwise might be.
467
468
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000469.. function:: isSequenceType(obj)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000471 Returns true if the object *obj* supports the sequence protocol. This returns true
Georg Brandl8ec7f652007-08-15 14:28:01 +0000472 for all objects which define sequence methods in C, and for all instance objects
473 defining :meth:`__getitem__`.
474
475 .. warning::
476
477 There is no reliable way to test if an instance supports the complete sequence
478 interface since the interface itself is ill-defined. This makes this test less
479 useful than it otherwise might be.
480
481Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
482their character equivalents. ::
483
484 >>> import operator
485 >>> d = {}
486 >>> keys = range(256)
487 >>> vals = map(chr, keys)
488 >>> map(operator.setitem, [d]*len(keys), keys, vals)
489
490.. XXX: find a better, readable, example
491
492The :mod:`operator` module also defines tools for generalized attribute and item
493lookups. These are useful for making fast field extractors as arguments for
494:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
495expect a function argument.
496
497
498.. function:: attrgetter(attr[, args...])
499
500 Return a callable object that fetches *attr* from its operand. If more than one
501 attribute is requested, returns a tuple of attributes. After,
502 ``f=attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
503 ``f=attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
504 b.date)``.
505
506 .. versionadded:: 2.4
507
508 .. versionchanged:: 2.5
509 Added support for multiple attributes.
510
511
512.. function:: itemgetter(item[, args...])
513
514 Return a callable object that fetches *item* from its operand. If more than one
515 item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the
516 call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call
517 ``f(b)`` returns ``(b[2], b[5], b[3])``.
518
519 .. versionadded:: 2.4
520
521 .. versionchanged:: 2.5
522 Added support for multiple item extraction.
523
524Examples::
525
526 >>> from operator import itemgetter
527 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
528 >>> getcount = itemgetter(1)
529 >>> map(getcount, inventory)
530 [3, 2, 5, 1]
531 >>> sorted(inventory, key=getcount)
532 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
533
534
535.. _operator-map:
536
537Mapping Operators to Functions
538------------------------------
539
540This table shows how abstract operations correspond to operator symbols in the
541Python syntax and the functions in the :mod:`operator` module.
542
543+-----------------------+-------------------------+---------------------------------+
544| Operation | Syntax | Function |
545+=======================+=========================+=================================+
546| Addition | ``a + b`` | ``add(a, b)`` |
547+-----------------------+-------------------------+---------------------------------+
548| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
549+-----------------------+-------------------------+---------------------------------+
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000550| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000551+-----------------------+-------------------------+---------------------------------+
552| Division | ``a / b`` | ``div(a, b)`` (without |
553| | | ``__future__.division``) |
554+-----------------------+-------------------------+---------------------------------+
555| Division | ``a / b`` | ``truediv(a, b)`` (with |
556| | | ``__future__.division``) |
557+-----------------------+-------------------------+---------------------------------+
558| Division | ``a // b`` | ``floordiv(a, b)`` |
559+-----------------------+-------------------------+---------------------------------+
560| Bitwise And | ``a & b`` | ``and_(a, b)`` |
561+-----------------------+-------------------------+---------------------------------+
562| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
563+-----------------------+-------------------------+---------------------------------+
564| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
565+-----------------------+-------------------------+---------------------------------+
566| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
567+-----------------------+-------------------------+---------------------------------+
568| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
569+-----------------------+-------------------------+---------------------------------+
570| Identity | ``a is b`` | ``is_(a, b)`` |
571+-----------------------+-------------------------+---------------------------------+
572| Identity | ``a is not b`` | ``is_not(a, b)`` |
573+-----------------------+-------------------------+---------------------------------+
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000574| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575+-----------------------+-------------------------+---------------------------------+
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000576| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000577+-----------------------+-------------------------+---------------------------------+
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000578| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579+-----------------------+-------------------------+---------------------------------+
580| Left Shift | ``a << b`` | ``lshift(a, b)`` |
581+-----------------------+-------------------------+---------------------------------+
582| Modulo | ``a % b`` | ``mod(a, b)`` |
583+-----------------------+-------------------------+---------------------------------+
584| Multiplication | ``a * b`` | ``mul(a, b)`` |
585+-----------------------+-------------------------+---------------------------------+
586| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
587+-----------------------+-------------------------+---------------------------------+
588| Negation (Logical) | ``not a`` | ``not_(a)`` |
589+-----------------------+-------------------------+---------------------------------+
590| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
591+-----------------------+-------------------------+---------------------------------+
592| Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` |
593+-----------------------+-------------------------+---------------------------------+
594| Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
595+-----------------------+-------------------------+---------------------------------+
596| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
597+-----------------------+-------------------------+---------------------------------+
598| Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
599+-----------------------+-------------------------+---------------------------------+
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000600| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000601+-----------------------+-------------------------+---------------------------------+
602| Subtraction | ``a - b`` | ``sub(a, b)`` |
603+-----------------------+-------------------------+---------------------------------+
Mark Summerfieldddca9f02007-09-13 14:54:30 +0000604| Truth Test | ``obj`` | ``truth(obj)`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000605+-----------------------+-------------------------+---------------------------------+
606| Ordering | ``a < b`` | ``lt(a, b)`` |
607+-----------------------+-------------------------+---------------------------------+
608| Ordering | ``a <= b`` | ``le(a, b)`` |
609+-----------------------+-------------------------+---------------------------------+
610| Equality | ``a == b`` | ``eq(a, b)`` |
611+-----------------------+-------------------------+---------------------------------+
612| Difference | ``a != b`` | ``ne(a, b)`` |
613+-----------------------+-------------------------+---------------------------------+
614| Ordering | ``a >= b`` | ``ge(a, b)`` |
615+-----------------------+-------------------------+---------------------------------+
616| Ordering | ``a > b`` | ``gt(a, b)`` |
617+-----------------------+-------------------------+---------------------------------+
618