/Doc/library/operator.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 650 lines · 410 code · 240 blank · 0 comment · 0 complexity · 37c5c813c5c4b4fbb08d5d5286aa09c4 MD5 · raw file

  1. :mod:`operator` --- Standard operators as functions
  2. ===================================================
  3. .. module:: operator
  4. :synopsis: Functions corresponding to the standard operators.
  5. .. sectionauthor:: Skip Montanaro <skip@automatrix.com>
  6. .. testsetup::
  7. import operator
  8. from operator import itemgetter
  9. The :mod:`operator` module exports a set of functions implemented in C
  10. corresponding to the intrinsic operators of Python. For example,
  11. ``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function
  12. names are those used for special class methods; variants without leading and
  13. trailing ``__`` are also provided for convenience.
  14. The functions fall into categories that perform object comparisons, logical
  15. operations, mathematical operations, sequence operations, and abstract type
  16. tests.
  17. The object comparison functions are useful for all objects, and are named after
  18. the rich comparison operators they support:
  19. .. function:: lt(a, b)
  20. le(a, b)
  21. eq(a, b)
  22. ne(a, b)
  23. ge(a, b)
  24. gt(a, b)
  25. __lt__(a, b)
  26. __le__(a, b)
  27. __eq__(a, b)
  28. __ne__(a, b)
  29. __ge__(a, b)
  30. __gt__(a, b)
  31. Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
  32. equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
  33. b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
  34. ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
  35. >= b``. Note that unlike the built-in :func:`cmp`, these functions can
  36. return any value, which may or may not be interpretable as a Boolean value.
  37. See :ref:`comparisons` for more information about rich comparisons.
  38. .. versionadded:: 2.2
  39. The logical operations are also generally applicable to all objects, and support
  40. truth tests, identity tests, and boolean operations:
  41. .. function:: not_(obj)
  42. __not__(obj)
  43. Return the outcome of :keyword:`not` *obj*. (Note that there is no
  44. :meth:`__not__` method for object instances; only the interpreter core defines
  45. this operation. The result is affected by the :meth:`__nonzero__` and
  46. :meth:`__len__` methods.)
  47. .. function:: truth(obj)
  48. Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
  49. equivalent to using the :class:`bool` constructor.
  50. .. function:: is_(a, b)
  51. Return ``a is b``. Tests object identity.
  52. .. versionadded:: 2.3
  53. .. function:: is_not(a, b)
  54. Return ``a is not b``. Tests object identity.
  55. .. versionadded:: 2.3
  56. The mathematical and bitwise operations are the most numerous:
  57. .. function:: abs(obj)
  58. __abs__(obj)
  59. Return the absolute value of *obj*.
  60. .. function:: add(a, b)
  61. __add__(a, b)
  62. Return ``a + b``, for *a* and *b* numbers.
  63. .. function:: and_(a, b)
  64. __and__(a, b)
  65. Return the bitwise and of *a* and *b*.
  66. .. function:: div(a, b)
  67. __div__(a, b)
  68. Return ``a / b`` when ``__future__.division`` is not in effect. This is
  69. also known as "classic" division.
  70. .. function:: floordiv(a, b)
  71. __floordiv__(a, b)
  72. Return ``a // b``.
  73. .. versionadded:: 2.2
  74. .. function:: inv(obj)
  75. invert(obj)
  76. __inv__(obj)
  77. __invert__(obj)
  78. Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
  79. .. versionadded:: 2.0
  80. The names :func:`invert` and :func:`__invert__`.
  81. .. function:: lshift(a, b)
  82. __lshift__(a, b)
  83. Return *a* shifted left by *b*.
  84. .. function:: mod(a, b)
  85. __mod__(a, b)
  86. Return ``a % b``.
  87. .. function:: mul(a, b)
  88. __mul__(a, b)
  89. Return ``a * b``, for *a* and *b* numbers.
  90. .. function:: neg(obj)
  91. __neg__(obj)
  92. Return *obj* negated.
  93. .. function:: or_(a, b)
  94. __or__(a, b)
  95. Return the bitwise or of *a* and *b*.
  96. .. function:: pos(obj)
  97. __pos__(obj)
  98. Return *obj* positive.
  99. .. function:: pow(a, b)
  100. __pow__(a, b)
  101. Return ``a ** b``, for *a* and *b* numbers.
  102. .. versionadded:: 2.3
  103. .. function:: rshift(a, b)
  104. __rshift__(a, b)
  105. Return *a* shifted right by *b*.
  106. .. function:: sub(a, b)
  107. __sub__(a, b)
  108. Return ``a - b``.
  109. .. function:: truediv(a, b)
  110. __truediv__(a, b)
  111. Return ``a / b`` when ``__future__.division`` is in effect. This is also
  112. known as "true" division.
  113. .. versionadded:: 2.2
  114. .. function:: xor(a, b)
  115. __xor__(a, b)
  116. Return the bitwise exclusive or of *a* and *b*.
  117. .. function:: index(a)
  118. __index__(a)
  119. Return *a* converted to an integer. Equivalent to ``a.__index__()``.
  120. .. versionadded:: 2.5
  121. Operations which work with sequences include:
  122. .. function:: concat(a, b)
  123. __concat__(a, b)
  124. Return ``a + b`` for *a* and *b* sequences.
  125. .. function:: contains(a, b)
  126. __contains__(a, b)
  127. Return the outcome of the test ``b in a``. Note the reversed operands.
  128. .. versionadded:: 2.0
  129. The name :func:`__contains__`.
  130. .. function:: countOf(a, b)
  131. Return the number of occurrences of *b* in *a*.
  132. .. function:: delitem(a, b)
  133. __delitem__(a, b)
  134. Remove the value of *a* at index *b*.
  135. .. function:: delslice(a, b, c)
  136. __delslice__(a, b, c)
  137. Delete the slice of *a* from index *b* to index *c-1*.
  138. .. deprecated:: 2.6
  139. This function is removed in Python 3.0. Use :func:`delitem` with a slice
  140. index.
  141. .. function:: getitem(a, b)
  142. __getitem__(a, b)
  143. Return the value of *a* at index *b*.
  144. .. function:: getslice(a, b, c)
  145. __getslice__(a, b, c)
  146. Return the slice of *a* from index *b* to index *c-1*.
  147. .. deprecated:: 2.6
  148. This function is removed in Python 3.0. Use :func:`getitem` with a slice
  149. index.
  150. .. function:: indexOf(a, b)
  151. Return the index of the first of occurrence of *b* in *a*.
  152. .. function:: repeat(a, b)
  153. __repeat__(a, b)
  154. .. deprecated:: 2.6
  155. This function is removed in Python 3.0. Use :func:`__mul__` instead.
  156. Return ``a * b`` where *a* is a sequence and *b* is an integer.
  157. .. function:: sequenceIncludes(...)
  158. .. deprecated:: 2.0
  159. Use :func:`contains` instead.
  160. Alias for :func:`contains`.
  161. .. function:: setitem(a, b, c)
  162. __setitem__(a, b, c)
  163. Set the value of *a* at index *b* to *c*.
  164. .. function:: setslice(a, b, c, v)
  165. __setslice__(a, b, c, v)
  166. Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
  167. .. deprecated:: 2.6
  168. This function is removed in Python 3.0. Use :func:`setitem` with a slice
  169. index.
  170. Example use of operator functions::
  171. >>> # Elementwise multiplication
  172. >>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
  173. [0, 20, 60, 120]
  174. >>> # Dot product
  175. >>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
  176. 200
  177. Many operations have an "in-place" version. The following functions provide a
  178. more primitive access to in-place operators than the usual syntax does; for
  179. example, the :term:`statement` ``x += y`` is equivalent to
  180. ``x = operator.iadd(x, y)``. Another way to put it is to say that
  181. ``z = operator.iadd(x, y)`` is equivalent to the compound statement
  182. ``z = x; z += y``.
  183. .. function:: iadd(a, b)
  184. __iadd__(a, b)
  185. ``a = iadd(a, b)`` is equivalent to ``a += b``.
  186. .. versionadded:: 2.5
  187. .. function:: iand(a, b)
  188. __iand__(a, b)
  189. ``a = iand(a, b)`` is equivalent to ``a &= b``.
  190. .. versionadded:: 2.5
  191. .. function:: iconcat(a, b)
  192. __iconcat__(a, b)
  193. ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
  194. .. versionadded:: 2.5
  195. .. function:: idiv(a, b)
  196. __idiv__(a, b)
  197. ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
  198. not in effect.
  199. .. versionadded:: 2.5
  200. .. function:: ifloordiv(a, b)
  201. __ifloordiv__(a, b)
  202. ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
  203. .. versionadded:: 2.5
  204. .. function:: ilshift(a, b)
  205. __ilshift__(a, b)
  206. ``a = ilshift(a, b)`` is equivalent to ``a <``\ ``<= b``.
  207. .. versionadded:: 2.5
  208. .. function:: imod(a, b)
  209. __imod__(a, b)
  210. ``a = imod(a, b)`` is equivalent to ``a %= b``.
  211. .. versionadded:: 2.5
  212. .. function:: imul(a, b)
  213. __imul__(a, b)
  214. ``a = imul(a, b)`` is equivalent to ``a *= b``.
  215. .. versionadded:: 2.5
  216. .. function:: ior(a, b)
  217. __ior__(a, b)
  218. ``a = ior(a, b)`` is equivalent to ``a |= b``.
  219. .. versionadded:: 2.5
  220. .. function:: ipow(a, b)
  221. __ipow__(a, b)
  222. ``a = ipow(a, b)`` is equivalent to ``a **= b``.
  223. .. versionadded:: 2.5
  224. .. function:: irepeat(a, b)
  225. __irepeat__(a, b)
  226. .. deprecated:: 2.6
  227. This function is removed in Python 3.0. Use :func:`__imul__` instead.
  228. ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
  229. *b* is an integer.
  230. .. versionadded:: 2.5
  231. .. function:: irshift(a, b)
  232. __irshift__(a, b)
  233. ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
  234. .. versionadded:: 2.5
  235. .. function:: isub(a, b)
  236. __isub__(a, b)
  237. ``a = isub(a, b)`` is equivalent to ``a -= b``.
  238. .. versionadded:: 2.5
  239. .. function:: itruediv(a, b)
  240. __itruediv__(a, b)
  241. ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
  242. is in effect.
  243. .. versionadded:: 2.5
  244. .. function:: ixor(a, b)
  245. __ixor__(a, b)
  246. ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
  247. .. versionadded:: 2.5
  248. The :mod:`operator` module also defines a few predicates to test the type of
  249. objects; however, these are not all reliable. It is preferable to test
  250. abstract base classes instead (see :mod:`collections` and
  251. :mod:`numbers` for details).
  252. .. function:: isCallable(obj)
  253. .. deprecated:: 2.0
  254. Use ``isinstance(x, collections.Callable)`` instead.
  255. Returns true if the object *obj* can be called like a function, otherwise it
  256. returns false. True is returned for functions, bound and unbound methods, class
  257. objects, and instance objects which support the :meth:`__call__` method.
  258. .. function:: isMappingType(obj)
  259. .. deprecated:: 2.6
  260. This function is removed in Python 3.0. Use ``isinstance(x, collections.Mapping)`` instead.
  261. Returns true if the object *obj* supports the mapping interface. This is true for
  262. dictionaries and all instance objects defining :meth:`__getitem__`.
  263. .. function:: isNumberType(obj)
  264. .. deprecated:: 2.6
  265. This function is removed in Python 3.0. Use ``isinstance(x, numbers.Number)`` instead.
  266. Returns true if the object *obj* represents a number. This is true for all
  267. numeric types implemented in C.
  268. .. function:: isSequenceType(obj)
  269. .. deprecated:: 2.6
  270. This function is removed in Python 3.0. Use ``isinstance(x, collections.Sequence)`` instead.
  271. Returns true if the object *obj* supports the sequence protocol. This returns true
  272. for all objects which define sequence methods in C, and for all instance objects
  273. defining :meth:`__getitem__`.
  274. The :mod:`operator` module also defines tools for generalized attribute and item
  275. lookups. These are useful for making fast field extractors as arguments for
  276. :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
  277. expect a function argument.
  278. .. function:: attrgetter(attr[, args...])
  279. Return a callable object that fetches *attr* from its operand. If more than one
  280. attribute is requested, returns a tuple of attributes. After,
  281. ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
  282. ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
  283. b.date)``.
  284. The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
  285. the call ``f(b)`` returns ``b.date.month``.
  286. .. versionadded:: 2.4
  287. .. versionchanged:: 2.5
  288. Added support for multiple attributes.
  289. .. versionchanged:: 2.6
  290. Added support for dotted attributes.
  291. .. function:: itemgetter(item[, args...])
  292. Return a callable object that fetches *item* from its operand using the
  293. operand's :meth:`__getitem__` method. If multiple items are specified,
  294. returns a tuple of lookup values. Equivalent to::
  295. def itemgetter(*items):
  296. if len(items) == 1:
  297. item = items[0]
  298. def g(obj):
  299. return obj[item]
  300. else:
  301. def g(obj):
  302. return tuple(obj[item] for item in items)
  303. return g
  304. The items can be any type accepted by the operand's :meth:`__getitem__`
  305. method. Dictionaries accept any hashable value. Lists, tuples, and
  306. strings accept an index or a slice:
  307. >>> itemgetter(1)('ABCDEFG')
  308. 'B'
  309. >>> itemgetter(1,3,5)('ABCDEFG')
  310. ('B', 'D', 'F')
  311. >>> itemgetter(slice(2,None))('ABCDEFG')
  312. 'CDEFG'
  313. .. versionadded:: 2.4
  314. .. versionchanged:: 2.5
  315. Added support for multiple item extraction.
  316. Example of using :func:`itemgetter` to retrieve specific fields from a
  317. tuple record:
  318. >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
  319. >>> getcount = itemgetter(1)
  320. >>> map(getcount, inventory)
  321. [3, 2, 5, 1]
  322. >>> sorted(inventory, key=getcount)
  323. [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
  324. .. function:: methodcaller(name[, args...])
  325. Return a callable object that calls the method *name* on its operand. If
  326. additional arguments and/or keyword arguments are given, they will be given
  327. to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
  328. returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
  329. call ``f(b)`` returns ``b.name('foo', bar=1)``.
  330. .. versionadded:: 2.6
  331. .. _operator-map:
  332. Mapping Operators to Functions
  333. ------------------------------
  334. This table shows how abstract operations correspond to operator symbols in the
  335. Python syntax and the functions in the :mod:`operator` module.
  336. +-----------------------+-------------------------+---------------------------------+
  337. | Operation | Syntax | Function |
  338. +=======================+=========================+=================================+
  339. | Addition | ``a + b`` | ``add(a, b)`` |
  340. +-----------------------+-------------------------+---------------------------------+
  341. | Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
  342. +-----------------------+-------------------------+---------------------------------+
  343. | Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
  344. +-----------------------+-------------------------+---------------------------------+
  345. | Division | ``a / b`` | ``div(a, b)`` (without |
  346. | | | ``__future__.division``) |
  347. +-----------------------+-------------------------+---------------------------------+
  348. | Division | ``a / b`` | ``truediv(a, b)`` (with |
  349. | | | ``__future__.division``) |
  350. +-----------------------+-------------------------+---------------------------------+
  351. | Division | ``a // b`` | ``floordiv(a, b)`` |
  352. +-----------------------+-------------------------+---------------------------------+
  353. | Bitwise And | ``a & b`` | ``and_(a, b)`` |
  354. +-----------------------+-------------------------+---------------------------------+
  355. | Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
  356. +-----------------------+-------------------------+---------------------------------+
  357. | Bitwise Inversion | ``~ a`` | ``invert(a)`` |
  358. +-----------------------+-------------------------+---------------------------------+
  359. | Bitwise Or | ``a | b`` | ``or_(a, b)`` |
  360. +-----------------------+-------------------------+---------------------------------+
  361. | Exponentiation | ``a ** b`` | ``pow(a, b)`` |
  362. +-----------------------+-------------------------+---------------------------------+
  363. | Identity | ``a is b`` | ``is_(a, b)`` |
  364. +-----------------------+-------------------------+---------------------------------+
  365. | Identity | ``a is not b`` | ``is_not(a, b)`` |
  366. +-----------------------+-------------------------+---------------------------------+
  367. | Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
  368. +-----------------------+-------------------------+---------------------------------+
  369. | Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
  370. +-----------------------+-------------------------+---------------------------------+
  371. | Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
  372. +-----------------------+-------------------------+---------------------------------+
  373. | Left Shift | ``a << b`` | ``lshift(a, b)`` |
  374. +-----------------------+-------------------------+---------------------------------+
  375. | Modulo | ``a % b`` | ``mod(a, b)`` |
  376. +-----------------------+-------------------------+---------------------------------+
  377. | Multiplication | ``a * b`` | ``mul(a, b)`` |
  378. +-----------------------+-------------------------+---------------------------------+
  379. | Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
  380. +-----------------------+-------------------------+---------------------------------+
  381. | Negation (Logical) | ``not a`` | ``not_(a)`` |
  382. +-----------------------+-------------------------+---------------------------------+
  383. | Right Shift | ``a >> b`` | ``rshift(a, b)`` |
  384. +-----------------------+-------------------------+---------------------------------+
  385. | Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
  386. +-----------------------+-------------------------+---------------------------------+
  387. | Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
  388. +-----------------------+-------------------------+---------------------------------+
  389. | Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
  390. +-----------------------+-------------------------+---------------------------------+
  391. | Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
  392. +-----------------------+-------------------------+---------------------------------+
  393. | String Formatting | ``s % obj`` | ``mod(s, obj)`` |
  394. +-----------------------+-------------------------+---------------------------------+
  395. | Subtraction | ``a - b`` | ``sub(a, b)`` |
  396. +-----------------------+-------------------------+---------------------------------+
  397. | Truth Test | ``obj`` | ``truth(obj)`` |
  398. +-----------------------+-------------------------+---------------------------------+
  399. | Ordering | ``a < b`` | ``lt(a, b)`` |
  400. +-----------------------+-------------------------+---------------------------------+
  401. | Ordering | ``a <= b`` | ``le(a, b)`` |
  402. +-----------------------+-------------------------+---------------------------------+
  403. | Equality | ``a == b`` | ``eq(a, b)`` |
  404. +-----------------------+-------------------------+---------------------------------+
  405. | Difference | ``a != b`` | ``ne(a, b)`` |
  406. +-----------------------+-------------------------+---------------------------------+
  407. | Ordering | ``a >= b`` | ``ge(a, b)`` |
  408. +-----------------------+-------------------------+---------------------------------+
  409. | Ordering | ``a > b`` | ``gt(a, b)`` |
  410. +-----------------------+-------------------------+---------------------------------+