operator.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. """
  2. Operator Interface
  3. This module exports a set of functions corresponding to the intrinsic
  4. operators of Python. For example, operator.add(x, y) is equivalent
  5. to the expression x+y. The function names are those used for special
  6. methods; variants without leading and trailing '__' are also provided
  7. for convenience.
  8. This is the pure Python implementation of the module.
  9. """
  10. __all__ = ['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf',
  11. 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand',
  12. 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul',
  13. 'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift',
  14. 'is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le',
  15. 'length_hint', 'lshift', 'lt', 'matmul', 'methodcaller', 'mod',
  16. 'mul', 'ne', 'neg', 'not_', 'or_', 'pos', 'pow', 'rshift',
  17. 'setitem', 'sub', 'truediv', 'truth', 'xor']
  18. from builtins import abs as _abs
  19. # Comparison Operations *******************************************************#
  20. def lt(a, b):
  21. "Same as a < b."
  22. return a < b
  23. def le(a, b):
  24. "Same as a <= b."
  25. return a <= b
  26. def eq(a, b):
  27. "Same as a == b."
  28. return a == b
  29. def ne(a, b):
  30. "Same as a != b."
  31. return a != b
  32. def ge(a, b):
  33. "Same as a >= b."
  34. return a >= b
  35. def gt(a, b):
  36. "Same as a > b."
  37. return a > b
  38. # Logical Operations **********************************************************#
  39. def not_(a):
  40. "Same as not a."
  41. return not a
  42. def truth(a):
  43. "Return True if a is true, False otherwise."
  44. return True if a else False
  45. def is_(a, b):
  46. "Same as a is b."
  47. return a is b
  48. def is_not(a, b):
  49. "Same as a is not b."
  50. return a is not b
  51. # Mathematical/Bitwise Operations *********************************************#
  52. def abs(a):
  53. "Same as abs(a)."
  54. return _abs(a)
  55. def add(a, b):
  56. "Same as a + b."
  57. return a + b
  58. def and_(a, b):
  59. "Same as a & b."
  60. return a & b
  61. def floordiv(a, b):
  62. "Same as a // b."
  63. return a // b
  64. def index(a):
  65. "Same as a.__index__()."
  66. return a.__index__()
  67. def inv(a):
  68. "Same as ~a."
  69. return ~a
  70. invert = inv
  71. def lshift(a, b):
  72. "Same as a << b."
  73. return a << b
  74. def mod(a, b):
  75. "Same as a % b."
  76. return a % b
  77. def mul(a, b):
  78. "Same as a * b."
  79. return a * b
  80. def matmul(a, b):
  81. "Same as a @ b."
  82. return a @ b
  83. def neg(a):
  84. "Same as -a."
  85. return -a
  86. def or_(a, b):
  87. "Same as a | b."
  88. return a | b
  89. def pos(a):
  90. "Same as +a."
  91. return +a
  92. def pow(a, b):
  93. "Same as a ** b."
  94. return a ** b
  95. def rshift(a, b):
  96. "Same as a >> b."
  97. return a >> b
  98. def sub(a, b):
  99. "Same as a - b."
  100. return a - b
  101. def truediv(a, b):
  102. "Same as a / b."
  103. return a / b
  104. def xor(a, b):
  105. "Same as a ^ b."
  106. return a ^ b
  107. # Sequence Operations *********************************************************#
  108. def concat(a, b):
  109. "Same as a + b, for a and b sequences."
  110. if not hasattr(a, '__getitem__'):
  111. msg = "'%s' object can't be concatenated" % type(a).__name__
  112. raise TypeError(msg)
  113. return a + b
  114. def contains(a, b):
  115. "Same as b in a (note reversed operands)."
  116. return b in a
  117. def countOf(a, b):
  118. "Return the number of items in a which are, or which equal, b."
  119. count = 0
  120. for i in a:
  121. if i is b or i == b:
  122. count += 1
  123. return count
  124. def delitem(a, b):
  125. "Same as del a[b]."
  126. del a[b]
  127. def getitem(a, b):
  128. "Same as a[b]."
  129. return a[b]
  130. def indexOf(a, b):
  131. "Return the first index of b in a."
  132. for i, j in enumerate(a):
  133. if j is b or j == b:
  134. return i
  135. else:
  136. raise ValueError('sequence.index(x): x not in sequence')
  137. def setitem(a, b, c):
  138. "Same as a[b] = c."
  139. a[b] = c
  140. def length_hint(obj, default=0):
  141. """
  142. Return an estimate of the number of items in obj.
  143. This is useful for presizing containers when building from an iterable.
  144. If the object supports len(), the result will be exact. Otherwise, it may
  145. over- or under-estimate by an arbitrary amount. The result will be an
  146. integer >= 0.
  147. """
  148. if not isinstance(default, int):
  149. msg = ("'%s' object cannot be interpreted as an integer" %
  150. type(default).__name__)
  151. raise TypeError(msg)
  152. try:
  153. return len(obj)
  154. except TypeError:
  155. pass
  156. try:
  157. hint = type(obj).__length_hint__
  158. except AttributeError:
  159. return default
  160. try:
  161. val = hint(obj)
  162. except TypeError:
  163. return default
  164. if val is NotImplemented:
  165. return default
  166. if not isinstance(val, int):
  167. msg = ('__length_hint__ must be integer, not %s' %
  168. type(val).__name__)
  169. raise TypeError(msg)
  170. if val < 0:
  171. msg = '__length_hint__() should return >= 0'
  172. raise ValueError(msg)
  173. return val
  174. # Generalized Lookup Objects **************************************************#
  175. class attrgetter:
  176. """
  177. Return a callable object that fetches the given attribute(s) from its operand.
  178. After f = attrgetter('name'), the call f(r) returns r.name.
  179. After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).
  180. After h = attrgetter('name.first', 'name.last'), the call h(r) returns
  181. (r.name.first, r.name.last).
  182. """
  183. __slots__ = ('_attrs', '_call')
  184. def __init__(self, attr, *attrs):
  185. if not attrs:
  186. if not isinstance(attr, str):
  187. raise TypeError('attribute name must be a string')
  188. self._attrs = (attr,)
  189. names = attr.split('.')
  190. def func(obj):
  191. for name in names:
  192. obj = getattr(obj, name)
  193. return obj
  194. self._call = func
  195. else:
  196. self._attrs = (attr,) + attrs
  197. getters = tuple(map(attrgetter, self._attrs))
  198. def func(obj):
  199. return tuple(getter(obj) for getter in getters)
  200. self._call = func
  201. def __call__(self, obj):
  202. return self._call(obj)
  203. def __repr__(self):
  204. return '%s.%s(%s)' % (self.__class__.__module__,
  205. self.__class__.__qualname__,
  206. ', '.join(map(repr, self._attrs)))
  207. def __reduce__(self):
  208. return self.__class__, self._attrs
  209. class itemgetter:
  210. """
  211. Return a callable object that fetches the given item(s) from its operand.
  212. After f = itemgetter(2), the call f(r) returns r[2].
  213. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
  214. """
  215. __slots__ = ('_items', '_call')
  216. def __init__(self, item, *items):
  217. if not items:
  218. self._items = (item,)
  219. def func(obj):
  220. return obj[item]
  221. self._call = func
  222. else:
  223. self._items = items = (item,) + items
  224. def func(obj):
  225. return tuple(obj[i] for i in items)
  226. self._call = func
  227. def __call__(self, obj):
  228. return self._call(obj)
  229. def __repr__(self):
  230. return '%s.%s(%s)' % (self.__class__.__module__,
  231. self.__class__.__name__,
  232. ', '.join(map(repr, self._items)))
  233. def __reduce__(self):
  234. return self.__class__, self._items
  235. class methodcaller:
  236. """
  237. Return a callable object that calls the given method on its operand.
  238. After f = methodcaller('name'), the call f(r) returns r.name().
  239. After g = methodcaller('name', 'date', foo=1), the call g(r) returns
  240. r.name('date', foo=1).
  241. """
  242. __slots__ = ('_name', '_args', '_kwargs')
  243. def __init__(self, name, /, *args, **kwargs):
  244. self._name = name
  245. if not isinstance(self._name, str):
  246. raise TypeError('method name must be a string')
  247. self._args = args
  248. self._kwargs = kwargs
  249. def __call__(self, obj):
  250. return getattr(obj, self._name)(*self._args, **self._kwargs)
  251. def __repr__(self):
  252. args = [repr(self._name)]
  253. args.extend(map(repr, self._args))
  254. args.extend('%s=%r' % (k, v) for k, v in self._kwargs.items())
  255. return '%s.%s(%s)' % (self.__class__.__module__,
  256. self.__class__.__name__,
  257. ', '.join(args))
  258. def __reduce__(self):
  259. if not self._kwargs:
  260. return self.__class__, (self._name,) + self._args
  261. else:
  262. from functools import partial
  263. return partial(self.__class__, self._name, **self._kwargs), self._args
  264. # In-place Operations *********************************************************#
  265. def iadd(a, b):
  266. "Same as a += b."
  267. a += b
  268. return a
  269. def iand(a, b):
  270. "Same as a &= b."
  271. a &= b
  272. return a
  273. def iconcat(a, b):
  274. "Same as a += b, for a and b sequences."
  275. if not hasattr(a, '__getitem__'):
  276. msg = "'%s' object can't be concatenated" % type(a).__name__
  277. raise TypeError(msg)
  278. a += b
  279. return a
  280. def ifloordiv(a, b):
  281. "Same as a //= b."
  282. a //= b
  283. return a
  284. def ilshift(a, b):
  285. "Same as a <<= b."
  286. a <<= b
  287. return a
  288. def imod(a, b):
  289. "Same as a %= b."
  290. a %= b
  291. return a
  292. def imul(a, b):
  293. "Same as a *= b."
  294. a *= b
  295. return a
  296. def imatmul(a, b):
  297. "Same as a @= b."
  298. a @= b
  299. return a
  300. def ior(a, b):
  301. "Same as a |= b."
  302. a |= b
  303. return a
  304. def ipow(a, b):
  305. "Same as a **= b."
  306. a **=b
  307. return a
  308. def irshift(a, b):
  309. "Same as a >>= b."
  310. a >>= b
  311. return a
  312. def isub(a, b):
  313. "Same as a -= b."
  314. a -= b
  315. return a
  316. def itruediv(a, b):
  317. "Same as a /= b."
  318. a /= b
  319. return a
  320. def ixor(a, b):
  321. "Same as a ^= b."
  322. a ^= b
  323. return a
  324. try:
  325. from _operator import *
  326. except ImportError:
  327. pass
  328. else:
  329. from _operator import __doc__
  330. # All of these "__func__ = func" assignments have to happen after importing
  331. # from _operator to make sure they're set to the right function
  332. __lt__ = lt
  333. __le__ = le
  334. __eq__ = eq
  335. __ne__ = ne
  336. __ge__ = ge
  337. __gt__ = gt
  338. __not__ = not_
  339. __abs__ = abs
  340. __add__ = add
  341. __and__ = and_
  342. __floordiv__ = floordiv
  343. __index__ = index
  344. __inv__ = inv
  345. __invert__ = invert
  346. __lshift__ = lshift
  347. __mod__ = mod
  348. __mul__ = mul
  349. __matmul__ = matmul
  350. __neg__ = neg
  351. __or__ = or_
  352. __pos__ = pos
  353. __pow__ = pow
  354. __rshift__ = rshift
  355. __sub__ = sub
  356. __truediv__ = truediv
  357. __xor__ = xor
  358. __concat__ = concat
  359. __contains__ = contains
  360. __delitem__ = delitem
  361. __getitem__ = getitem
  362. __setitem__ = setitem
  363. __iadd__ = iadd
  364. __iand__ = iand
  365. __iconcat__ = iconcat
  366. __ifloordiv__ = ifloordiv
  367. __ilshift__ = ilshift
  368. __imod__ = imod
  369. __imul__ = imul
  370. __imatmul__ = imatmul
  371. __ior__ = ior
  372. __ipow__ = ipow
  373. __irshift__ = irshift
  374. __isub__ = isub
  375. __itruediv__ = itruediv
  376. __ixor__ = ixor