Debian Codegraph @

Doc/library/operator.rst

raw
1 :mod:`!operator` --- Standard operators as functions
2 ====================================================
3
4 .. module:: operator
5 :synopsis: Functions corresponding to the standard operators.
6
7 .. sectionauthor:: Skip Montanaro <[email protected]>
8
9 **Source code:** :source:`Lib/operator.py`
10
11 .. testsetup::
12
13 import operator
14 from operator import itemgetter, iadd
15
16 --------------
17
18 The :mod:`operator` module exports a set of efficient functions corresponding to
19 the intrinsic operators of Python. For example, ``operator.add(x, y)`` is
20 equivalent to the expression ``x+y``. Many function names are those used for
21 special methods, without the double underscores. For backward compatibility,
22 many of these have a variant with the double underscores kept. The variants
23 without the double underscores are preferred for clarity.
24
25 The functions fall into categories that perform object comparisons, logical
26 operations, mathematical operations and sequence operations.
27
28 The object comparison functions are useful for all objects, and are named after
29 the rich comparison operators they support:
30
31
32 .. function:: lt(a, b)
33 le(a, b)
34 eq(a, b)
35 ne(a, b)
36 ge(a, b)
37 gt(a, b)
38 __lt__(a, b)
39 __le__(a, b)
40 __eq__(a, b)
41 __ne__(a, b)
42 __ge__(a, b)
43 __gt__(a, b)
44
45 Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
46 equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
47 b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
48 ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
49 >= b``. Note that these functions can return any value, which may
50 or may not be interpretable as a Boolean value. See
51 :ref:`comparisons` for more information about rich comparisons.
52
53
54 The logical operations are also generally applicable to all objects, and support
55 truth tests, identity tests, and boolean operations:
56
57
58 .. function:: not_(obj)
59 __not__(obj)
60
61 Return the outcome of :keyword:`not` *obj*. (Note that there is no
62 :meth:`!__not__` method for object instances; only the interpreter core defines
63 this operation. The result is affected by the :meth:`~object.__bool__` and
64 :meth:`~object.__len__` methods.)
65
66
67 .. function:: truth(obj)
68
69 Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
70 equivalent to using the :class:`bool` constructor.
71
72
73 .. function:: is_(a, b)
74
75 Return ``a is b``. Tests object identity.
76
77
78 .. function:: is_not(a, b)
79
80 Return ``a is not b``. Tests object identity.
81
82
83 The mathematical and bitwise operations are the most numerous:
84
85
86 .. function:: abs(obj)
87 __abs__(obj)
88
89 Return the absolute value of *obj*.
90
91
92 .. function:: add(a, b)
93 __add__(a, b)
94
95 Return ``a + b``, for *a* and *b* numbers.
96
97
98 .. function:: and_(a, b)
99 __and__(a, b)
100
101 Return the bitwise and of *a* and *b*.
102
103
104 .. function:: floordiv(a, b)
105 __floordiv__(a, b)
106
107 Return ``a // b``.
108
109
110 .. function:: index(a)
111 __index__(a)
112
113 Return *a* converted to an integer. Equivalent to ``a.__index__()``.
114
115 .. versionchanged:: 3.10
116 The result always has exact type :class:`int`. Previously, the result
117 could have been an instance of a subclass of ``int``.
118
119
120 .. function:: inv(obj)
121 invert(obj)
122 __inv__(obj)
123 __invert__(obj)
124
125 Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
126
127
128 .. function:: lshift(a, b)
129 __lshift__(a, b)
130
131 Return *a* shifted left by *b*.
132
133
134 .. function:: mod(a, b)
135 __mod__(a, b)
136
137 Return ``a % b``.
138
139
140 .. function:: mul(a, b)
141 __mul__(a, b)
142
143 Return ``a * b``, for *a* and *b* numbers.
144
145
146 .. function:: matmul(a, b)
147 __matmul__(a, b)
148
149 Return ``a @ b``.
150
151 .. versionadded:: 3.5
152
153
154 .. function:: neg(obj)
155 __neg__(obj)
156
157 Return *obj* negated (``-obj``).
158
159
160 .. function:: or_(a, b)
161 __or__(a, b)
162
163 Return the bitwise or of *a* and *b*.
164
165
166 .. function:: pos(obj)
167 __pos__(obj)
168
169 Return *obj* positive (``+obj``).
170
171
172 .. function:: pow(a, b)
173 __pow__(a, b)
174
175 Return ``a ** b``, for *a* and *b* numbers.
176
177
178 .. function:: rshift(a, b)
179 __rshift__(a, b)
180
181 Return *a* shifted right by *b*.
182
183
184 .. function:: sub(a, b)
185 __sub__(a, b)
186
187 Return ``a - b``.
188
189
190 .. function:: truediv(a, b)
191 __truediv__(a, b)
192
193 Return ``a / b`` where 2/3 is .66 rather than 0. This is also known as
194 "true" division.
195
196
197 .. function:: xor(a, b)
198 __xor__(a, b)
199
200 Return the bitwise exclusive or of *a* and *b*.
201
202
203 Operations which work with sequences (some of them with mappings too) include:
204
205 .. function:: concat(a, b)
206 __concat__(a, b)
207
208 Return ``a + b`` for *a* and *b* sequences.
209
210
211 .. function:: contains(a, b)
212 __contains__(a, b)
213
214 Return the outcome of the test ``b in a``. Note the reversed operands.
215
216
217 .. function:: countOf(a, b)
218
219 Return the number of occurrences of *b* in *a*.
220
221
222 .. function:: delitem(a, b)
223 __delitem__(a, b)
224
225 Remove the value of *a* at index *b*.
226
227
228 .. function:: getitem(a, b)
229 __getitem__(a, b)
230
231 Return the value of *a* at index *b*.
232
233
234 .. function:: indexOf(a, b)
235
236 Return the index of the first of occurrence of *b* in *a*.
237
238
239 .. function:: setitem(a, b, c)
240 __setitem__(a, b, c)
241
242 Set the value of *a* at index *b* to *c*.
243
244
245 .. function:: length_hint(obj, default=0)
246
247 Return an estimated length for the object *obj*. First try to return its
248 actual length, then an estimate using :meth:`object.__length_hint__`, and
249 finally return the default value.
250
251 .. versionadded:: 3.4
252
253
254 The following operation works with callables:
255
256 .. function:: call(obj, /, *args, **kwargs)
257 __call__(obj, /, *args, **kwargs)
258
259 Return ``obj(*args, **kwargs)``.
260
261 .. versionadded:: 3.11
262
263
264 The :mod:`operator` module also defines tools for generalized attribute and item
265 lookups. These are useful for making fast field extractors as arguments for
266 :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
267 expect a function argument.
268
269
270 .. function:: attrgetter(attr)
271 attrgetter(*attrs)
272
273 Return a callable object that fetches *attr* from its operand.
274 If more than one attribute is requested, returns a tuple of attributes.
275 The attribute names can also contain dots. For example:
276
277 * After ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``.
278
279 * After ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns
280 ``(b.name, b.date)``.
281
282 * After ``f = attrgetter('name.first', 'name.last')``, the call ``f(b)``
283 returns ``(b.name.first, b.name.last)``.
284
285 Equivalent to::
286
287 def attrgetter(*items):
288 if any(not isinstance(item, str) for item in items):
289 raise TypeError('attribute name must be a string')
290 if len(items) == 1:
291 attr = items[0]
292 def g(obj):
293 return resolve_attr(obj, attr)
294 else:
295 def g(obj):
296 return tuple(resolve_attr(obj, attr) for attr in items)
297 return g
298
299 def resolve_attr(obj, attr):
300 for name in attr.split("."):
301 obj = getattr(obj, name)
302 return obj
303
304
305 .. function:: itemgetter(item)
306 itemgetter(*items)
307
308 Return a callable object that fetches *item* from its operand using the
309 operand's :meth:`~object.__getitem__` method. If multiple items are specified,
310 returns a tuple of lookup values. For example:
311
312 * After ``f = itemgetter(2)``, the call ``f(r)`` returns ``r[2]``.
313
314 * After ``g = itemgetter(2, 5, 3)``, the call ``g(r)`` returns
315 ``(r[2], r[5], r[3])``.
316
317 Equivalent to::
318
319 def itemgetter(*items):
320 if len(items) == 1:
321 item = items[0]
322 def g(obj):
323 return obj[item]
324 else:
325 def g(obj):
326 return tuple(obj[item] for item in items)
327 return g
328
329 The items can be any type accepted by the operand's :meth:`~object.__getitem__`
330 method. Dictionaries accept any :term:`hashable` value. Lists, tuples, and
331 strings accept an index or a slice:
332
333 >>> itemgetter(1)('ABCDEFG')
334 'B'
335 >>> itemgetter(1, 3, 5)('ABCDEFG')
336 ('B', 'D', 'F')
337 >>> itemgetter(slice(2, None))('ABCDEFG')
338 'CDEFG'
339 >>> soldier = dict(rank='captain', name='dotterbart')
340 >>> itemgetter('rank')(soldier)
341 'captain'
342
343 Example of using :func:`itemgetter` to retrieve specific fields from a
344 tuple record:
345
346 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
347 >>> getcount = itemgetter(1)
348 >>> list(map(getcount, inventory))
349 [3, 2, 5, 1]
350 >>> sorted(inventory, key=getcount)
351 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
352
353
354 .. function:: methodcaller(name, /, *args, **kwargs)
355
356 Return a callable object that calls the method *name* on its operand. If
357 additional arguments and/or keyword arguments are given, they will be given
358 to the method as well. For example:
359
360 * After ``f = methodcaller('name')``, the call ``f(b)`` returns ``b.name()``.
361
362 * After ``f = methodcaller('name', 'foo', bar=1)``, the call ``f(b)``
363 returns ``b.name('foo', bar=1)``.
364
365 Equivalent to::
366
367 def methodcaller(name, /, *args, **kwargs):
368 def caller(obj):
369 return getattr(obj, name)(*args, **kwargs)
370 return caller
371
372
373 .. _operator-map:
374
375 Mapping Operators to Functions
376 ------------------------------
377
378 This table shows how abstract operations correspond to operator symbols in the
379 Python syntax and the functions in the :mod:`operator` module.
380
381 +-----------------------+-------------------------+---------------------------------------+
382 | Operation | Syntax | Function |
383 +=======================+=========================+=======================================+
384 | Addition | ``a + b`` | ``add(a, b)`` |
385 +-----------------------+-------------------------+---------------------------------------+
386 | Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
387 +-----------------------+-------------------------+---------------------------------------+
388 | Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
389 +-----------------------+-------------------------+---------------------------------------+
390 | Division | ``a / b`` | ``truediv(a, b)`` |
391 +-----------------------+-------------------------+---------------------------------------+
392 | Division | ``a // b`` | ``floordiv(a, b)`` |
393 +-----------------------+-------------------------+---------------------------------------+
394 | Bitwise And | ``a & b`` | ``and_(a, b)`` |
395 +-----------------------+-------------------------+---------------------------------------+
396 | Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
397 +-----------------------+-------------------------+---------------------------------------+
398 | Bitwise Inversion | ``~ a`` | ``invert(a)`` |
399 +-----------------------+-------------------------+---------------------------------------+
400 | Bitwise Or | ``a | b`` | ``or_(a, b)`` |
401 +-----------------------+-------------------------+---------------------------------------+
402 | Exponentiation | ``a ** b`` | ``pow(a, b)`` |
403 +-----------------------+-------------------------+---------------------------------------+
404 | Identity | ``a is b`` | ``is_(a, b)`` |
405 +-----------------------+-------------------------+---------------------------------------+
406 | Identity | ``a is not b`` | ``is_not(a, b)`` |
407 +-----------------------+-------------------------+---------------------------------------+
408 | Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
409 +-----------------------+-------------------------+---------------------------------------+
410 | Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
411 +-----------------------+-------------------------+---------------------------------------+
412 | Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
413 +-----------------------+-------------------------+---------------------------------------+
414 | Left Shift | ``a << b`` | ``lshift(a, b)`` |
415 +-----------------------+-------------------------+---------------------------------------+
416 | Modulo | ``a % b`` | ``mod(a, b)`` |
417 +-----------------------+-------------------------+---------------------------------------+
418 | Multiplication | ``a * b`` | ``mul(a, b)`` |
419 +-----------------------+-------------------------+---------------------------------------+
420 | Matrix Multiplication | ``a @ b`` | ``matmul(a, b)`` |
421 +-----------------------+-------------------------+---------------------------------------+
422 | Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
423 +-----------------------+-------------------------+---------------------------------------+
424 | Negation (Logical) | ``not a`` | ``not_(a)`` |
425 +-----------------------+-------------------------+---------------------------------------+
426 | Positive | ``+ a`` | ``pos(a)`` |
427 +-----------------------+-------------------------+---------------------------------------+
428 | Right Shift | ``a >> b`` | ``rshift(a, b)`` |
429 +-----------------------+-------------------------+---------------------------------------+
430 | Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
431 +-----------------------+-------------------------+---------------------------------------+
432 | Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
433 +-----------------------+-------------------------+---------------------------------------+
434 | Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
435 +-----------------------+-------------------------+---------------------------------------+
436 | String Formatting | ``s % obj`` | ``mod(s, obj)`` |
437 +-----------------------+-------------------------+---------------------------------------+
438 | Subtraction | ``a - b`` | ``sub(a, b)`` |
439 +-----------------------+-------------------------+---------------------------------------+
440 | Truth Test | ``obj`` | ``truth(obj)`` |
441 +-----------------------+-------------------------+---------------------------------------+
442 | Ordering | ``a < b`` | ``lt(a, b)`` |
443 +-----------------------+-------------------------+---------------------------------------+
444 | Ordering | ``a <= b`` | ``le(a, b)`` |
445 +-----------------------+-------------------------+---------------------------------------+
446 | Equality | ``a == b`` | ``eq(a, b)`` |
447 +-----------------------+-------------------------+---------------------------------------+
448 | Difference | ``a != b`` | ``ne(a, b)`` |
449 +-----------------------+-------------------------+---------------------------------------+
450 | Ordering | ``a >= b`` | ``ge(a, b)`` |
451 +-----------------------+-------------------------+---------------------------------------+
452 | Ordering | ``a > b`` | ``gt(a, b)`` |
453 +-----------------------+-------------------------+---------------------------------------+
454
455 In-place Operators
456 ------------------
457
458 Many operations have an "in-place" version. Listed below are functions
459 providing a more primitive access to in-place operators than the usual syntax
460 does; for example, the :term:`statement` ``x += y`` is equivalent to
461 ``x = operator.iadd(x, y)``. Another way to put it is to say that
462 ``z = operator.iadd(x, y)`` is equivalent to the compound statement
463 ``z = x; z += y``.
464
465 In those examples, note that when an in-place method is called, the computation
466 and assignment are performed in two separate steps. The in-place functions
467 listed below only do the first step, calling the in-place method. The second
468 step, assignment, is not handled.
469
470 For immutable targets such as strings, numbers, and tuples, the updated
471 value is computed, but not assigned back to the input variable:
472
473 >>> a = 'hello'
474 >>> iadd(a, ' world')
475 'hello world'
476 >>> a
477 'hello'
478
479 For mutable targets such as lists and dictionaries, the in-place method
480 will perform the update, so no subsequent assignment is necessary:
481
482 >>> s = ['h', 'e', 'l', 'l', 'o']
483 >>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
484 ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
485 >>> s
486 ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
487
488 .. function:: iadd(a, b)
489 __iadd__(a, b)
490
491 ``a = iadd(a, b)`` is equivalent to ``a += b``.
492
493
494 .. function:: iand(a, b)
495 __iand__(a, b)
496
497 ``a = iand(a, b)`` is equivalent to ``a &= b``.
498
499
500 .. function:: iconcat(a, b)
501 __iconcat__(a, b)
502
503 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
504
505
506 .. function:: ifloordiv(a, b)
507 __ifloordiv__(a, b)
508
509 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
510
511
512 .. function:: ilshift(a, b)
513 __ilshift__(a, b)
514
515 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
516
517
518 .. function:: imod(a, b)
519 __imod__(a, b)
520
521 ``a = imod(a, b)`` is equivalent to ``a %= b``.
522
523
524 .. function:: imul(a, b)
525 __imul__(a, b)
526
527 ``a = imul(a, b)`` is equivalent to ``a *= b``.
528
529
530 .. function:: imatmul(a, b)
531 __imatmul__(a, b)
532
533 ``a = imatmul(a, b)`` is equivalent to ``a @= b``.
534
535 .. versionadded:: 3.5
536
537
538 .. function:: ior(a, b)
539 __ior__(a, b)
540
541 ``a = ior(a, b)`` is equivalent to ``a |= b``.
542
543
544 .. function:: ipow(a, b)
545 __ipow__(a, b)
546
547 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
548
549
550 .. function:: irshift(a, b)
551 __irshift__(a, b)
552
553 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
554
555
556 .. function:: isub(a, b)
557 __isub__(a, b)
558
559 ``a = isub(a, b)`` is equivalent to ``a -= b``.
560
561
562 .. function:: itruediv(a, b)
563 __itruediv__(a, b)
564
565 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
566
567
568 .. function:: ixor(a, b)
569 __ixor__(a, b)
570
571 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.