ยปCore Development>Code coverage>Lib/operator.py

Python code coverage for Lib/operator.py

#countcontent
1n/a"""
2n/aOperator Interface
3n/a
4n/aThis module exports a set of functions corresponding to the intrinsic
5n/aoperators of Python. For example, operator.add(x, y) is equivalent
6n/ato the expression x+y. The function names are those used for special
7n/amethods; variants without leading and trailing '__' are also provided
8n/afor convenience.
9n/a
10n/aThis is the pure Python implementation of the module.
11n/a"""
12n/a
13n/a__all__ = ['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf',
14n/a 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand',
15n/a 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul',
16n/a 'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift',
17n/a 'is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le',
18n/a 'length_hint', 'lshift', 'lt', 'matmul', 'methodcaller', 'mod',
19n/a 'mul', 'ne', 'neg', 'not_', 'or_', 'pos', 'pow', 'rshift',
20n/a 'setitem', 'sub', 'truediv', 'truth', 'xor']
21n/a
22n/afrom builtins import abs as _abs
23n/a
24n/a
25n/a# Comparison Operations *******************************************************#
26n/a
27n/adef lt(a, b):
28n/a "Same as a < b."
29n/a return a < b
30n/a
31n/adef le(a, b):
32n/a "Same as a <= b."
33n/a return a <= b
34n/a
35n/adef eq(a, b):
36n/a "Same as a == b."
37n/a return a == b
38n/a
39n/adef ne(a, b):
40n/a "Same as a != b."
41n/a return a != b
42n/a
43n/adef ge(a, b):
44n/a "Same as a >= b."
45n/a return a >= b
46n/a
47n/adef gt(a, b):
48n/a "Same as a > b."
49n/a return a > b
50n/a
51n/a# Logical Operations **********************************************************#
52n/a
53n/adef not_(a):
54n/a "Same as not a."
55n/a return not a
56n/a
57n/adef truth(a):
58n/a "Return True if a is true, False otherwise."
59n/a return True if a else False
60n/a
61n/adef is_(a, b):
62n/a "Same as a is b."
63n/a return a is b
64n/a
65n/adef is_not(a, b):
66n/a "Same as a is not b."
67n/a return a is not b
68n/a
69n/a# Mathematical/Bitwise Operations *********************************************#
70n/a
71n/adef abs(a):
72n/a "Same as abs(a)."
73n/a return _abs(a)
74n/a
75n/adef add(a, b):
76n/a "Same as a + b."
77n/a return a + b
78n/a
79n/adef and_(a, b):
80n/a "Same as a & b."
81n/a return a & b
82n/a
83n/adef floordiv(a, b):
84n/a "Same as a // b."
85n/a return a // b
86n/a
87n/adef index(a):
88n/a "Same as a.__index__()."
89n/a return a.__index__()
90n/a
91n/adef inv(a):
92n/a "Same as ~a."
93n/a return ~a
94n/ainvert = inv
95n/a
96n/adef lshift(a, b):
97n/a "Same as a << b."
98n/a return a << b
99n/a
100n/adef mod(a, b):
101n/a "Same as a % b."
102n/a return a % b
103n/a
104n/adef mul(a, b):
105n/a "Same as a * b."
106n/a return a * b
107n/a
108n/adef matmul(a, b):
109n/a "Same as a @ b."
110n/a return a @ b
111n/a
112n/adef neg(a):
113n/a "Same as -a."
114n/a return -a
115n/a
116n/adef or_(a, b):
117n/a "Same as a | b."
118n/a return a | b
119n/a
120n/adef pos(a):
121n/a "Same as +a."
122n/a return +a
123n/a
124n/adef pow(a, b):
125n/a "Same as a ** b."
126n/a return a ** b
127n/a
128n/adef rshift(a, b):
129n/a "Same as a >> b."
130n/a return a >> b
131n/a
132n/adef sub(a, b):
133n/a "Same as a - b."
134n/a return a - b
135n/a
136n/adef truediv(a, b):
137n/a "Same as a / b."
138n/a return a / b
139n/a
140n/adef xor(a, b):
141n/a "Same as a ^ b."
142n/a return a ^ b
143n/a
144n/a# Sequence Operations *********************************************************#
145n/a
146n/adef concat(a, b):
147n/a "Same as a + b, for a and b sequences."
148n/a if not hasattr(a, '__getitem__'):
149n/a msg = "'%s' object can't be concatenated" % type(a).__name__
150n/a raise TypeError(msg)
151n/a return a + b
152n/a
153n/adef contains(a, b):
154n/a "Same as b in a (note reversed operands)."
155n/a return b in a
156n/a
157n/adef countOf(a, b):
158n/a "Return the number of times b occurs in a."
159n/a count = 0
160n/a for i in a:
161n/a if i == b:
162n/a count += 1
163n/a return count
164n/a
165n/adef delitem(a, b):
166n/a "Same as del a[b]."
167n/a del a[b]
168n/a
169n/adef getitem(a, b):
170n/a "Same as a[b]."
171n/a return a[b]
172n/a
173n/adef indexOf(a, b):
174n/a "Return the first index of b in a."
175n/a for i, j in enumerate(a):
176n/a if j == b:
177n/a return i
178n/a else:
179n/a raise ValueError('sequence.index(x): x not in sequence')
180n/a
181n/adef setitem(a, b, c):
182n/a "Same as a[b] = c."
183n/a a[b] = c
184n/a
185n/adef length_hint(obj, default=0):
186n/a """
187n/a Return an estimate of the number of items in obj.
188n/a This is useful for presizing containers when building from an iterable.
189n/a
190n/a If the object supports len(), the result will be exact. Otherwise, it may
191n/a over- or under-estimate by an arbitrary amount. The result will be an
192n/a integer >= 0.
193n/a """
194n/a if not isinstance(default, int):
195n/a msg = ("'%s' object cannot be interpreted as an integer" %
196n/a type(default).__name__)
197n/a raise TypeError(msg)
198n/a
199n/a try:
200n/a return len(obj)
201n/a except TypeError:
202n/a pass
203n/a
204n/a try:
205n/a hint = type(obj).__length_hint__
206n/a except AttributeError:
207n/a return default
208n/a
209n/a try:
210n/a val = hint(obj)
211n/a except TypeError:
212n/a return default
213n/a if val is NotImplemented:
214n/a return default
215n/a if not isinstance(val, int):
216n/a msg = ('__length_hint__ must be integer, not %s' %
217n/a type(val).__name__)
218n/a raise TypeError(msg)
219n/a if val < 0:
220n/a msg = '__length_hint__() should return >= 0'
221n/a raise ValueError(msg)
222n/a return val
223n/a
224n/a# Generalized Lookup Objects **************************************************#
225n/a
226n/aclass attrgetter:
227n/a """
228n/a Return a callable object that fetches the given attribute(s) from its operand.
229n/a After f = attrgetter('name'), the call f(r) returns r.name.
230n/a After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).
231n/a After h = attrgetter('name.first', 'name.last'), the call h(r) returns
232n/a (r.name.first, r.name.last).
233n/a """
234n/a __slots__ = ('_attrs', '_call')
235n/a
236n/a def __init__(self, attr, *attrs):
237n/a if not attrs:
238n/a if not isinstance(attr, str):
239n/a raise TypeError('attribute name must be a string')
240n/a self._attrs = (attr,)
241n/a names = attr.split('.')
242n/a def func(obj):
243n/a for name in names:
244n/a obj = getattr(obj, name)
245n/a return obj
246n/a self._call = func
247n/a else:
248n/a self._attrs = (attr,) + attrs
249n/a getters = tuple(map(attrgetter, self._attrs))
250n/a def func(obj):
251n/a return tuple(getter(obj) for getter in getters)
252n/a self._call = func
253n/a
254n/a def __call__(self, obj):
255n/a return self._call(obj)
256n/a
257n/a def __repr__(self):
258n/a return '%s.%s(%s)' % (self.__class__.__module__,
259n/a self.__class__.__qualname__,
260n/a ', '.join(map(repr, self._attrs)))
261n/a
262n/a def __reduce__(self):
263n/a return self.__class__, self._attrs
264n/a
265n/aclass itemgetter:
266n/a """
267n/a Return a callable object that fetches the given item(s) from its operand.
268n/a After f = itemgetter(2), the call f(r) returns r[2].
269n/a After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
270n/a """
271n/a __slots__ = ('_items', '_call')
272n/a
273n/a def __init__(self, item, *items):
274n/a if not items:
275n/a self._items = (item,)
276n/a def func(obj):
277n/a return obj[item]
278n/a self._call = func
279n/a else:
280n/a self._items = items = (item,) + items
281n/a def func(obj):
282n/a return tuple(obj[i] for i in items)
283n/a self._call = func
284n/a
285n/a def __call__(self, obj):
286n/a return self._call(obj)
287n/a
288n/a def __repr__(self):
289n/a return '%s.%s(%s)' % (self.__class__.__module__,
290n/a self.__class__.__name__,
291n/a ', '.join(map(repr, self._items)))
292n/a
293n/a def __reduce__(self):
294n/a return self.__class__, self._items
295n/a
296n/aclass methodcaller:
297n/a """
298n/a Return a callable object that calls the given method on its operand.
299n/a After f = methodcaller('name'), the call f(r) returns r.name().
300n/a After g = methodcaller('name', 'date', foo=1), the call g(r) returns
301n/a r.name('date', foo=1).
302n/a """
303n/a __slots__ = ('_name', '_args', '_kwargs')
304n/a
305n/a def __init__(*args, **kwargs):
306n/a if len(args) < 2:
307n/a msg = "methodcaller needs at least one argument, the method name"
308n/a raise TypeError(msg)
309n/a self = args[0]
310n/a self._name = args[1]
311n/a if not isinstance(self._name, str):
312n/a raise TypeError('method name must be a string')
313n/a self._args = args[2:]
314n/a self._kwargs = kwargs
315n/a
316n/a def __call__(self, obj):
317n/a return getattr(obj, self._name)(*self._args, **self._kwargs)
318n/a
319n/a def __repr__(self):
320n/a args = [repr(self._name)]
321n/a args.extend(map(repr, self._args))
322n/a args.extend('%s=%r' % (k, v) for k, v in self._kwargs.items())
323n/a return '%s.%s(%s)' % (self.__class__.__module__,
324n/a self.__class__.__name__,
325n/a ', '.join(args))
326n/a
327n/a def __reduce__(self):
328n/a if not self._kwargs:
329n/a return self.__class__, (self._name,) + self._args
330n/a else:
331n/a from functools import partial
332n/a return partial(self.__class__, self._name, **self._kwargs), self._args
333n/a
334n/a
335n/a# In-place Operations *********************************************************#
336n/a
337n/adef iadd(a, b):
338n/a "Same as a += b."
339n/a a += b
340n/a return a
341n/a
342n/adef iand(a, b):
343n/a "Same as a &= b."
344n/a a &= b
345n/a return a
346n/a
347n/adef iconcat(a, b):
348n/a "Same as a += b, for a and b sequences."
349n/a if not hasattr(a, '__getitem__'):
350n/a msg = "'%s' object can't be concatenated" % type(a).__name__
351n/a raise TypeError(msg)
352n/a a += b
353n/a return a
354n/a
355n/adef ifloordiv(a, b):
356n/a "Same as a //= b."
357n/a a //= b
358n/a return a
359n/a
360n/adef ilshift(a, b):
361n/a "Same as a <<= b."
362n/a a <<= b
363n/a return a
364n/a
365n/adef imod(a, b):
366n/a "Same as a %= b."
367n/a a %= b
368n/a return a
369n/a
370n/adef imul(a, b):
371n/a "Same as a *= b."
372n/a a *= b
373n/a return a
374n/a
375n/adef imatmul(a, b):
376n/a "Same as a @= b."
377n/a a @= b
378n/a return a
379n/a
380n/adef ior(a, b):
381n/a "Same as a |= b."
382n/a a |= b
383n/a return a
384n/a
385n/adef ipow(a, b):
386n/a "Same as a **= b."
387n/a a **=b
388n/a return a
389n/a
390n/adef irshift(a, b):
391n/a "Same as a >>= b."
392n/a a >>= b
393n/a return a
394n/a
395n/adef isub(a, b):
396n/a "Same as a -= b."
397n/a a -= b
398n/a return a
399n/a
400n/adef itruediv(a, b):
401n/a "Same as a /= b."
402n/a a /= b
403n/a return a
404n/a
405n/adef ixor(a, b):
406n/a "Same as a ^= b."
407n/a a ^= b
408n/a return a
409n/a
410n/a
411n/atry:
412n/a from _operator import *
413n/aexcept ImportError:
414n/a pass
415n/aelse:
416n/a from _operator import __doc__
417n/a
418n/a# All of these "__func__ = func" assignments have to happen after importing
419n/a# from _operator to make sure they're set to the right function
420n/a__lt__ = lt
421n/a__le__ = le
422n/a__eq__ = eq
423n/a__ne__ = ne
424n/a__ge__ = ge
425n/a__gt__ = gt
426n/a__not__ = not_
427n/a__abs__ = abs
428n/a__add__ = add
429n/a__and__ = and_
430n/a__floordiv__ = floordiv
431n/a__index__ = index
432n/a__inv__ = inv
433n/a__invert__ = invert
434n/a__lshift__ = lshift
435n/a__mod__ = mod
436n/a__mul__ = mul
437n/a__matmul__ = matmul
438n/a__neg__ = neg
439n/a__or__ = or_
440n/a__pos__ = pos
441n/a__pow__ = pow
442n/a__rshift__ = rshift
443n/a__sub__ = sub
444n/a__truediv__ = truediv
445n/a__xor__ = xor
446n/a__concat__ = concat
447n/a__contains__ = contains
448n/a__delitem__ = delitem
449n/a__getitem__ = getitem
450n/a__setitem__ = setitem
451n/a__iadd__ = iadd
452n/a__iand__ = iand
453n/a__iconcat__ = iconcat
454n/a__ifloordiv__ = ifloordiv
455n/a__ilshift__ = ilshift
456n/a__imod__ = imod
457n/a__imul__ = imul
458n/a__imatmul__ = imatmul
459n/a__ior__ = ior
460n/a__ipow__ = ipow
461n/a__irshift__ = irshift
462n/a__isub__ = isub
463n/a__itruediv__ = itruediv
464n/a__ixor__ = ixor