operator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 times b occurs in a."
  119. count = 0
  120. for i in a:
  121. if 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 == 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__(*args, **kwargs):
  244. if len(args) < 2:
  245. msg = "methodcaller needs at least one argument, the method name"
  246. raise TypeError(msg)
  247. self = args[0]
  248. self._name = args[1]
  249. if not isinstance(self._name, str):
  250. raise TypeError('method name must be a string')
  251. self._args = args[2:]
  252. self._kwargs = kwargs
  253. def __call__(self, obj):
  254. return getattr(obj, self._name)(*self._args, **self._kwargs)
  255. def __repr__(self):
  256. args = [repr(self._name)]
  257. args.extend(map(repr, self._args))
  258. args.extend('%s=%r' % (k, v) for k, v in self._kwargs.items())
  259. return '%s.%s(%s)' % (self.__class__.__module__,
  260. self.__class__.__name__,
  261. ', '.join(args))
  262. def __reduce__(self):
  263. if not self._kwargs:
  264. return self.__class__, (self._name,) + self._args
  265. else:
  266. from functools import partial
  267. return partial(self.__class__, self._name, **self._kwargs), self._args
  268. # In-place Operations *********************************************************#
  269. def iadd(a, b):
  270. "Same as a += b."
  271. a += b
  272. return a
  273. def iand(a, b):
  274. "Same as a &= b."
  275. a &= b
  276. return a
  277. def iconcat(a, b):
  278. "Same as a += b, for a and b sequences."
  279. if not hasattr(a, '__getitem__'):
  280. msg = "'%s' object can't be concatenated" % type(a).__name__
  281. raise TypeError(msg)
  282. a += b
  283. return a
  284. def ifloordiv(a, b):
  285. "Same as a //= b."
  286. a //= b
  287. return a
  288. def ilshift(a, b):
  289. "Same as a <<= b."
  290. a <<= b
  291. return a
  292. def imod(a, b):
  293. "Same as a %= b."
  294. a %= b
  295. return a
  296. def imul(a, b):
  297. "Same as a *= b."
  298. a *= b
  299. return a
  300. def imatmul(a, b):
  301. "Same as a @= b."
  302. a @= b
  303. return a
  304. def ior(a, b):
  305. "Same as a |= b."
  306. a |= b
  307. return a
  308. def ipow(a, b):
  309. "Same as a **= b."
  310. a **=b
  311. return a
  312. def irshift(a, b):
  313. "Same as a >>= b."
  314. a >>= b
  315. return a
  316. def isub(a, b):
  317. "Same as a -= b."
  318. a -= b
  319. return a
  320. def itruediv(a, b):
  321. "Same as a /= b."
  322. a /= b
  323. return a
  324. def ixor(a, b):
  325. "Same as a ^= b."
  326. a ^= b
  327. return a
  328. try:
  329. from _operator import *
  330. except ImportError:
  331. pass
  332. else:
  333. from _operator import __doc__
  334. # All of these "__func__ = func" assignments have to happen after importing
  335. # from _operator to make sure they're set to the right function
  336. __lt__ = lt
  337. __le__ = le
  338. __eq__ = eq
  339. __ne__ = ne
  340. __ge__ = ge
  341. __gt__ = gt
  342. __not__ = not_
  343. __abs__ = abs
  344. __add__ = add
  345. __and__ = and_
  346. __floordiv__ = floordiv
  347. __index__ = index
  348. __inv__ = inv
  349. __invert__ = invert
  350. __lshift__ = lshift
  351. __mod__ = mod
  352. __mul__ = mul
  353. __matmul__ = matmul
  354. __neg__ = neg
  355. __or__ = or_
  356. __pos__ = pos
  357. __pow__ = pow
  358. __rshift__ = rshift
  359. __sub__ = sub
  360. __truediv__ = truediv
  361. __xor__ = xor
  362. __concat__ = concat
  363. __contains__ = contains
  364. __delitem__ = delitem
  365. __getitem__ = getitem
  366. __setitem__ = setitem
  367. __iadd__ = iadd
  368. __iand__ = iand
  369. __iconcat__ = iconcat
  370. __ifloordiv__ = ifloordiv
  371. __ilshift__ = ilshift
  372. __imod__ = imod
  373. __imul__ = imul
  374. __imatmul__ = imatmul
  375. __ior__ = ior
  376. __ipow__ = ipow
  377. __irshift__ = irshift
  378. __isub__ = isub
  379. __itruediv__ = itruediv
  380. __ixor__ = ixor