operator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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', 'call', '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. # Other Operations ************************************************************#
  175. def call(obj, /, *args, **kwargs):
  176. """Same as obj(*args, **kwargs)."""
  177. return obj(*args, **kwargs)
  178. # Generalized Lookup Objects **************************************************#
  179. class attrgetter:
  180. """
  181. Return a callable object that fetches the given attribute(s) from its operand.
  182. After f = attrgetter('name'), the call f(r) returns r.name.
  183. After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).
  184. After h = attrgetter('name.first', 'name.last'), the call h(r) returns
  185. (r.name.first, r.name.last).
  186. """
  187. __slots__ = ('_attrs', '_call')
  188. def __init__(self, attr, *attrs):
  189. if not attrs:
  190. if not isinstance(attr, str):
  191. raise TypeError('attribute name must be a string')
  192. self._attrs = (attr,)
  193. names = attr.split('.')
  194. def func(obj):
  195. for name in names:
  196. obj = getattr(obj, name)
  197. return obj
  198. self._call = func
  199. else:
  200. self._attrs = (attr,) + attrs
  201. getters = tuple(map(attrgetter, self._attrs))
  202. def func(obj):
  203. return tuple(getter(obj) for getter in getters)
  204. self._call = func
  205. def __call__(self, obj):
  206. return self._call(obj)
  207. def __repr__(self):
  208. return '%s.%s(%s)' % (self.__class__.__module__,
  209. self.__class__.__qualname__,
  210. ', '.join(map(repr, self._attrs)))
  211. def __reduce__(self):
  212. return self.__class__, self._attrs
  213. class itemgetter:
  214. """
  215. Return a callable object that fetches the given item(s) from its operand.
  216. After f = itemgetter(2), the call f(r) returns r[2].
  217. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
  218. """
  219. __slots__ = ('_items', '_call')
  220. def __init__(self, item, *items):
  221. if not items:
  222. self._items = (item,)
  223. def func(obj):
  224. return obj[item]
  225. self._call = func
  226. else:
  227. self._items = items = (item,) + items
  228. def func(obj):
  229. return tuple(obj[i] for i in items)
  230. self._call = func
  231. def __call__(self, obj):
  232. return self._call(obj)
  233. def __repr__(self):
  234. return '%s.%s(%s)' % (self.__class__.__module__,
  235. self.__class__.__name__,
  236. ', '.join(map(repr, self._items)))
  237. def __reduce__(self):
  238. return self.__class__, self._items
  239. class methodcaller:
  240. """
  241. Return a callable object that calls the given method on its operand.
  242. After f = methodcaller('name'), the call f(r) returns r.name().
  243. After g = methodcaller('name', 'date', foo=1), the call g(r) returns
  244. r.name('date', foo=1).
  245. """
  246. __slots__ = ('_name', '_args', '_kwargs')
  247. def __init__(self, name, /, *args, **kwargs):
  248. self._name = name
  249. if not isinstance(self._name, str):
  250. raise TypeError('method name must be a string')
  251. self._args = args
  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. __call__ = call
  347. __floordiv__ = floordiv
  348. __index__ = index
  349. __inv__ = inv
  350. __invert__ = invert
  351. __lshift__ = lshift
  352. __mod__ = mod
  353. __mul__ = mul
  354. __matmul__ = matmul
  355. __neg__ = neg
  356. __or__ = or_
  357. __pos__ = pos
  358. __pow__ = pow
  359. __rshift__ = rshift
  360. __sub__ = sub
  361. __truediv__ = truediv
  362. __xor__ = xor
  363. __concat__ = concat
  364. __contains__ = contains
  365. __delitem__ = delitem
  366. __getitem__ = getitem
  367. __setitem__ = setitem
  368. __iadd__ = iadd
  369. __iand__ = iand
  370. __iconcat__ = iconcat
  371. __ifloordiv__ = ifloordiv
  372. __ilshift__ = ilshift
  373. __imod__ = imod
  374. __imul__ = imul
  375. __imatmul__ = imatmul
  376. __ior__ = ior
  377. __ipow__ = ipow
  378. __irshift__ = irshift
  379. __isub__ = isub
  380. __itruediv__ = itruediv
  381. __ixor__ = ixor