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 ``a & 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 ``~obj``.
140
141
142 .. function:: lshift(a, b)
143 __lshift__(a, b)
144
145 Return ``a << 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``.
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 ``a | b``.
178
179
180 .. function:: pos(obj)
181 __pos__(obj)
182
183 Return ``+obj``.
184
185
186 .. function:: pow(a, b)
187 __pow__(a, b)
188
189 Return ``a ** b``.
190
191
192 .. function:: rshift(a, b)
193 __rshift__(a, b)
194
195 Return ``a >> 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 ``a ^ 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, or | ``a & b`` | ``and_(a, b)`` |
409 | Intersection | | |
410 +-----------------------+-------------------------+---------------------------------------+
411 | Bitwise Exclusive Or, | ``a ^ b`` | ``xor(a, b)`` |
412 | or Symmetric | | |
413 | Difference | | |
414 +-----------------------+-------------------------+---------------------------------------+
415 | Bitwise Inversion, or | ``~ a`` | ``invert(a)`` |
416 | Complement | | |
417 +-----------------------+-------------------------+---------------------------------------+
418 | Bitwise Or, or | ``a | b`` | ``or_(a, b)`` |
419 | Union | | |
420 +-----------------------+-------------------------+---------------------------------------+
421 | Exponentiation | ``a ** b`` | ``pow(a, b)`` |
422 +-----------------------+-------------------------+---------------------------------------+
423 | Identity | ``a is b`` | ``is_(a, b)`` |
424 +-----------------------+-------------------------+---------------------------------------+
425 | Identity | ``a is not b`` | ``is_not(a, b)`` |
426 +-----------------------+-------------------------+---------------------------------------+
427 | Identity | ``a is None`` | ``is_none(a)`` |
428 +-----------------------+-------------------------+---------------------------------------+
429 | Identity | ``a is not None`` | ``is_not_none(a)`` |
430 +-----------------------+-------------------------+---------------------------------------+
431 | Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
432 +-----------------------+-------------------------+---------------------------------------+
433 | Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
434 +-----------------------+-------------------------+---------------------------------------+
435 | Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
436 +-----------------------+-------------------------+---------------------------------------+
437 | Left Shift | ``a << b`` | ``lshift(a, b)`` |
438 +-----------------------+-------------------------+---------------------------------------+
439 | Modulo | ``a % b`` | ``mod(a, b)`` |
440 +-----------------------+-------------------------+---------------------------------------+
441 | Multiplication | ``a * b`` | ``mul(a, b)`` |
442 +-----------------------+-------------------------+---------------------------------------+
443 | Matrix Multiplication | ``a @ b`` | ``matmul(a, b)`` |
444 +-----------------------+-------------------------+---------------------------------------+
445 | Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
446 +-----------------------+-------------------------+---------------------------------------+
447 | Negation (Logical) | ``not a`` | ``not_(a)`` |
448 +-----------------------+-------------------------+---------------------------------------+
449 | Positive | ``+ a`` | ``pos(a)`` |
450 +-----------------------+-------------------------+---------------------------------------+
451 | Right Shift | ``a >> b`` | ``rshift(a, b)`` |
452 +-----------------------+-------------------------+---------------------------------------+
453 | Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` |
454 +-----------------------+-------------------------+---------------------------------------+
455 | Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` |
456 +-----------------------+-------------------------+---------------------------------------+
457 | Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` |
458 +-----------------------+-------------------------+---------------------------------------+
459 | String Formatting | ``s % obj`` | ``mod(s, obj)`` |
460 +-----------------------+-------------------------+---------------------------------------+
461 | Subtraction | ``a - b`` | ``sub(a, b)`` |
462 +-----------------------+-------------------------+---------------------------------------+
463 | Truth Test | ``obj`` | ``truth(obj)`` |
464 +-----------------------+-------------------------+---------------------------------------+
465 | Ordering | ``a < b`` | ``lt(a, b)`` |
466 +-----------------------+-------------------------+---------------------------------------+
467 | Ordering | ``a <= b`` | ``le(a, b)`` |
468 +-----------------------+-------------------------+---------------------------------------+
469 | Equality | ``a == b`` | ``eq(a, b)`` |
470 +-----------------------+-------------------------+---------------------------------------+
471 | Difference | ``a != b`` | ``ne(a, b)`` |
472 +-----------------------+-------------------------+---------------------------------------+
473 | Ordering | ``a >= b`` | ``ge(a, b)`` |
474 +-----------------------+-------------------------+---------------------------------------+
475 | Ordering | ``a > b`` | ``gt(a, b)`` |
476 +-----------------------+-------------------------+---------------------------------------+
477
478 In-place Operators
479 ------------------
480
481 Many operations have an "in-place" version. Listed below are functions
482 providing a more primitive access to in-place operators than the usual syntax
483 does; for example, the :term:`statement` ``x += y`` is equivalent to
484 ``x = operator.iadd(x, y)``. Another way to put it is to say that
485 ``z = operator.iadd(x, y)`` is equivalent to the compound statement
486 ``z = x; z += y``.
487
488 In those examples, note that when an in-place method is called, the computation
489 and assignment are performed in two separate steps. The in-place functions
490 listed below only do the first step, calling the in-place method. The second
491 step, assignment, is not handled.
492
493 For immutable targets such as strings, numbers, and tuples, the updated
494 value is computed, but not assigned back to the input variable:
495
496 >>> a = 'hello'
497 >>> iadd(a, ' world')
498 'hello world'
499 >>> a
500 'hello'
501
502 For mutable targets such as lists and dictionaries, the in-place method
503 will perform the update, so no subsequent assignment is necessary:
504
505 >>> s = ['h', 'e', 'l', 'l', 'o']
506 >>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
507 ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
508 >>> s
509 ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
510
511 .. function:: iadd(a, b)
512 __iadd__(a, b)
513
514 ``a = iadd(a, b)`` is equivalent to ``a += b``.
515
516
517 .. function:: iand(a, b)
518 __iand__(a, b)
519
520 ``a = iand(a, b)`` is equivalent to ``a &= b``.
521
522
523 .. function:: iconcat(a, b)
524 __iconcat__(a, b)
525
526 ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
527
528
529 .. function:: ifloordiv(a, b)
530 __ifloordiv__(a, b)
531
532 ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
533
534
535 .. function:: ilshift(a, b)
536 __ilshift__(a, b)
537
538 ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
539
540
541 .. function:: imod(a, b)
542 __imod__(a, b)
543
544 ``a = imod(a, b)`` is equivalent to ``a %= b``.
545
546
547 .. function:: imul(a, b)
548 __imul__(a, b)
549
550 ``a = imul(a, b)`` is equivalent to ``a *= b``.
551
552
553 .. function:: imatmul(a, b)
554 __imatmul__(a, b)
555
556 ``a = imatmul(a, b)`` is equivalent to ``a @= b``.
557
558 .. versionadded:: 3.5
559
560
561 .. function:: ior(a, b)
562 __ior__(a, b)
563
564 ``a = ior(a, b)`` is equivalent to ``a |= b``.
565
566
567 .. function:: ipow(a, b)
568 __ipow__(a, b)
569
570 ``a = ipow(a, b)`` is equivalent to ``a **= b``.
571
572
573 .. function:: irshift(a, b)
574 __irshift__(a, b)
575
576 ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
577
578
579 .. function:: isub(a, b)
580 __isub__(a, b)
581
582 ``a = isub(a, b)`` is equivalent to ``a -= b``.
583
584
585 .. function:: itruediv(a, b)
586 __itruediv__(a, b)
587
588 ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
589
590
591 .. function:: ixor(a, b)
592 __ixor__(a, b)
593
594 ``a = ixor(a, b)`` is equivalent to ``a ^= b``.