blob: 4e8556907265cbbf52f8ad7841bd88d0e96efd59 [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
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
51.. function:: not_(o)
52 __not__(o)
53
54 Return the outcome of :keyword:`not` *o*. (Note that there is no
55 :meth:`__not__` method for object instances; only the interpreter core defines
56 this operation. The result is affected by the :meth:`__bool__` and
57 :meth:`__len__` methods.)
58
59
60.. function:: truth(o)
61
62 Return :const:`True` if *o* is true, and :const:`False` otherwise. This is
63 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
82.. function:: abs(o)
83 __abs__(o)
84
85 Return the absolute value of *o*.
86
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
115.. function:: inv(o)
116 invert(o)
117 __inv__(o)
118 __invert__(o)
119
120 Return the bitwise inverse of the number *o*. This is equivalent to ``~o``.
121
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
144.. function:: neg(o)
145 __neg__(o)
146
147 Return *o* negated.
148
149
150.. function:: or_(a, b)
151 __or__(a, b)
152
153 Return the bitwise or of *a* and *b*.
154
155
156.. function:: pos(o)
157 __pos__(o)
158
159 Return *o* positive.
160
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
283example, the statement ``x += y`` is equivalent to ``x = operator.iadd(x, y)``.
284Another way to put it is to say that ``z = operator.iadd(x, y)`` is equivalent
285to the compound statement ``z = x; z += y``.
286
287
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
424 >>> o = C()
425 >>> operator.isMappingType(o)
426 True
427
428
429.. function:: isCallable(o)
430
431 .. deprecated:: 2.0
432 Use the :func:`callable` built-in function instead.
433
434 Returns true if the object *o* can be called like a function, otherwise it
435 returns false. True is returned for functions, bound and unbound methods, class
436 objects, and instance objects which support the :meth:`__call__` method.
437
438
439.. function:: isMappingType(o)
440
441 Returns true if the object *o* supports the mapping interface. This is true for
442 dictionaries and all instance objects defining :meth:`__getitem__`.
443
444 .. warning::
445
446 There is no reliable way to test if an instance supports the complete mapping
447 protocol since the interface itself is ill-defined. This makes this test less
448 useful than it otherwise might be.
449
450
451.. function:: isNumberType(o)
452
453 Returns true if the object *o* represents a number. This is true for all
454 numeric types implemented in C.
455
456 .. warning::
457
458 There is no reliable way to test if an instance supports the complete numeric
459 interface since the interface itself is ill-defined. This makes this test less
460 useful than it otherwise might be.
461
462
463.. function:: isSequenceType(o)
464
465 Returns true if the object *o* supports the sequence protocol. This returns true
466 for all objects which define sequence methods in C, and for all instance objects
467 defining :meth:`__getitem__`.
468
469 .. warning::
470
471 There is no reliable way to test if an instance supports the complete sequence
472 interface since the interface itself is ill-defined. This makes this test less
473 useful than it otherwise might be.
474
475Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
476their character equivalents. ::
477
478 >>> import operator
479 >>> d = {}
480 >>> keys = range(256)
481 >>> vals = map(chr, keys)
482 >>> map(operator.setitem, [d]*len(keys), keys, vals)
483
484.. XXX: find a better, readable, example
485
486The :mod:`operator` module also defines tools for generalized attribute and item
487lookups. These are useful for making fast field extractors as arguments for
488:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
489expect a function argument.
490
491
492.. function:: attrgetter(attr[, args...])
493
494 Return a callable object that fetches *attr* from its operand. If more than one
495 attribute is requested, returns a tuple of attributes. After,
496 ``f=attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
497 ``f=attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
498 b.date)``.
499
500 .. versionadded:: 2.4
501
502 .. versionchanged:: 2.5
503 Added support for multiple attributes.
504
505
506.. function:: itemgetter(item[, args...])
507
508 Return a callable object that fetches *item* from its operand. If more than one
509 item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the
510 call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call
511 ``f(b)`` returns ``(b[2], b[5], b[3])``.
512
513 .. versionadded:: 2.4
514
515 .. versionchanged:: 2.5
516 Added support for multiple item extraction.
517
518Examples::
519
520 >>> from operator import itemgetter
521 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
522 >>> getcount = itemgetter(1)
523 >>> map(getcount, inventory)
524 [3, 2, 5, 1]
525 >>> sorted(inventory, key=getcount)
526 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
527
528
529.. _operator-map:
530
531Mapping Operators to Functions
532------------------------------
533
534This table shows how abstract operations correspond to operator symbols in the
535Python syntax and the functions in the :mod:`operator` module.
536
537+-----------------------+-------------------------+---------------------------------+
538| Operation | Syntax | Function |
539+=======================+=========================+=================================+
540| Addition | ``a + b`` | ``add(a, b)`` |
541+-----------------------+-------------------------+---------------------------------+
542| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
543+-----------------------+-------------------------+---------------------------------+
544| Containment Test | ``o in seq`` | ``contains(seq, o)`` |
545+-----------------------+-------------------------+---------------------------------+
546| Division | ``a / b`` | ``div(a, b)`` (without |
547| | | ``__future__.division``) |
548+-----------------------+-------------------------+---------------------------------+
549| Division | ``a / b`` | ``truediv(a, b)`` (with |
550| | | ``__future__.division``) |
551+-----------------------+-------------------------+---------------------------------+
552| Division | ``a // b`` | ``floordiv(a, b)`` |
553+-----------------------+-------------------------+---------------------------------+
554| Bitwise And | ``a & b`` | ``and_(a, b)`` |
555+-----------------------+-------------------------+---------------------------------+
556| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
557+-----------------------+-------------------------+---------------------------------+
558| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
559+-----------------------+-------------------------+---------------------------------+
560| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
561+-----------------------+-------------------------+---------------------------------+
562| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
563+-----------------------+-------------------------+---------------------------------+
564| Identity | ``a is b`` | ``is_(a, b)`` |
565+-----------------------+-------------------------+---------------------------------+
566| Identity | ``a is not b`` | ``is_not(a, b)`` |
567+-----------------------+-------------------------+---------------------------------+
568| Indexed Assignment | ``o[k] = v`` | ``setitem(o, k, v)`` |
569+-----------------------+-------------------------+---------------------------------+
570| Indexed Deletion | ``del o[k]`` | ``delitem(o, k)`` |
571+-----------------------+-------------------------+---------------------------------+
572| Indexing | ``o[k]`` | ``getitem(o, k)`` |
573+-----------------------+-------------------------+---------------------------------+
574| Left Shift | ``a << b`` | ``lshift(a, b)`` |
575+-----------------------+-------------------------+---------------------------------+
576| Modulo | ``a % b`` | ``mod(a, b)`` |
577+-----------------------+-------------------------+---------------------------------+
578| Multiplication | ``a * b`` | ``mul(a, b)`` |
579+-----------------------+-------------------------+---------------------------------+
580| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
581+-----------------------+-------------------------+---------------------------------+
582| Negation (Logical) | ``not a`` | ``not_(a)`` |
583+-----------------------+-------------------------+---------------------------------+
584| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
585+-----------------------+-------------------------+---------------------------------+
586| Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` |
587+-----------------------+-------------------------+---------------------------------+
588| Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
589+-----------------------+-------------------------+---------------------------------+
590| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
591+-----------------------+-------------------------+---------------------------------+
592| Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
593+-----------------------+-------------------------+---------------------------------+
594| String Formatting | ``s % o`` | ``mod(s, o)`` |
595+-----------------------+-------------------------+---------------------------------+
596| Subtraction | ``a - b`` | ``sub(a, b)`` |
597+-----------------------+-------------------------+---------------------------------+
598| Truth Test | ``o`` | ``truth(o)`` |
599+-----------------------+-------------------------+---------------------------------+
600| Ordering | ``a < b`` | ``lt(a, b)`` |
601+-----------------------+-------------------------+---------------------------------+
602| Ordering | ``a <= b`` | ``le(a, b)`` |
603+-----------------------+-------------------------+---------------------------------+
604| Equality | ``a == b`` | ``eq(a, b)`` |
605+-----------------------+-------------------------+---------------------------------+
606| Difference | ``a != b`` | ``ne(a, b)`` |
607+-----------------------+-------------------------+---------------------------------+
608| Ordering | ``a >= b`` | ``ge(a, b)`` |
609+-----------------------+-------------------------+---------------------------------+
610| Ordering | ``a > b`` | ``gt(a, b)`` |
611+-----------------------+-------------------------+---------------------------------+
612