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