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