9.9. operator — Standard operators as functions¶
The operator module exports a set of functions implemented in C
corresponding to the intrinsic operators of Python. For example,
operator.add(x, y) is equivalent to the expression x+y. The function
names are those used for special class methods; variants without leading and
trailing __ are also provided for convenience.
The functions fall into categories that perform object comparisons, logical operations, mathematical operations, sequence operations, and abstract type tests.
The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:
-
operator.lt(a, b)¶ -
operator.le(a, b)¶ -
operator.eq(a, b)¶ -
operator.ne(a, b)¶ -
operator.ge(a, b)¶ -
operator.gt(a, b)¶ -
operator.__lt__(a, b)¶ -
operator.__le__(a, b)¶ -
operator.__eq__(a, b)¶ -
operator.__ne__(a, b)¶ -
operator.__ge__(a, b)¶ -
operator.__gt__(a, b)¶ Perform “rich comparisons” between a and b. Specifically,
lt(a, b)is equivalent toa < b,le(a, b)is equivalent toa <= b,eq(a, b)is equivalent toa == b,ne(a, b)is equivalent toa != b,gt(a, b)is equivalent toa > bandge(a, b)is equivalent toa >= b. Note that unlike the built-incmp(), these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.New in version 2.2:
New in version 2.2.
The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations:
-
operator.not_(obj)¶ -
operator.__not__(obj)¶ Return the outcome of
notobj. (Note that there is no__not__()method for object instances; only the interpreter core defines this operation. The result is affected by the__nonzero__()and__len__()methods.)
-
operator.truth(obj)¶ Return
Trueif obj is true, andFalseotherwise. This is equivalent to using theboolconstructor.
-
operator.is_(a, b)¶ Return
a is b. Tests object identity.New in version 2.3:
New in version 2.3.