Theoperator module exports a set of functions implemented in Ccorresponding to the intrinsic operators of Python. For example,operator.add(x,y) is equivalent to the expressionx+y. The functionnames are those used for special class methods; variants without leading andtrailing__ are also provided for convenience.
The functions fall into categories that perform object comparisons, logicaloperations, mathematical operations, sequence operations, and abstract typetests.
The object comparison functions are useful for all objects, and are named afterthe rich comparison operators they support:
Perform “rich comparisons” betweena andb. Specifically,lt(a,b) isequivalent 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>b andge(a,b) is equivalent toa>=b. Note that unlike the built-incmp(), these functions canreturn any value, which may or may not be interpretable as a Boolean value.SeeComparisons for more information about rich comparisons.
New in version 2.2.
The logical operations are also generally applicable to all objects, and supporttruth tests, identity tests, and boolean operations:
Returnaisb. Tests object identity.
New in version 2.3.
Returnaisnotb. Tests object identity.
New in version 2.3.
The mathematical and bitwise operations are the most numerous:
Return the bitwise inverse of the numberobj. This is equivalent to~obj.
New in version 2.0:The namesinvert() and__invert__().
Returna/b when__future__.division is in effect. This is alsoknown as “true” division.
New in version 2.2.
Returna converted to an integer. Equivalent toa.__index__().
New in version 2.5.
Operations which work with sequences include:
Return the outcome of the testbina. Note the reversed operands.
New in version 2.0:The name__contains__().
Deprecated since version 2.0:Usecontains() instead.
Alias forcontains().
Many operations have an “in-place” version. The following functions provide amore primitive access to in-place operators than the usual syntax does; forexample, thestatementx+=y is equivalent tox=operator.iadd(x,y). Another way to put it is to say thatz=operator.iadd(x,y) is equivalent to the compound statementz=x;z+=y.
a=iconcat(a,b) is equivalent toa+=b fora andb sequences.
New in version 2.5.
a=idiv(a,b) is equivalent toa/=b when__future__.division isnot in effect.
New in version 2.5.
a=ifloordiv(a,b) is equivalent toa//=b.
New in version 2.5.
a=ilshift(a,b) is equivalent toa<<=b.
New in version 2.5.
a=irepeat(a,b) is equivalent toa*=b wherea is a sequence andb is an integer.
New in version 2.5.
a=irshift(a,b) is equivalent toa>>=b.
New in version 2.5.
a=itruediv(a,b) is equivalent toa/=b when__future__.divisionis in effect.
New in version 2.5.
Theoperator module also defines a few predicates to test the type ofobjects.
Note
Be careful not to misinterpret the results of these functions; onlyisCallable() has any measure of reliability with instance objects.For example:
>>>classC:...pass...>>>importoperator>>>obj=C()>>>operator.isMappingType(obj)True
Note
Python 3 is expected to introduce abstract base classes forcollection types, so it should be possible to write, for example,isinstance(obj,collections.Mapping) andisinstance(obj,collections.Sequence).
Deprecated since version 2.0:Use thecallable() built-in function instead.
Returns true if the objectobj can be called like a function, otherwise itreturns false. True is returned for functions, bound and unbound methods, classobjects, and instance objects which support the__call__() method.
Returns true if the objectobj supports the mapping interface. This is true fordictionaries and all instance objects defining__getitem__().
Warning
There is no reliable way to test if an instance supports the complete mappingprotocol since the interface itself is ill-defined. This makes this test lessuseful than it otherwise might be.
Returns true if the objectobj represents a number. This is true for allnumeric types implemented in C.
Warning
There is no reliable way to test if an instance supports the complete numericinterface since the interface itself is ill-defined. This makes this test lessuseful than it otherwise might be.
Returns true if the objectobj supports the sequence protocol. This returns truefor all objects which define sequence methods in C, and for all instance objectsdefining__getitem__().
Warning
There is no reliable way to test if an instance supports the complete sequenceinterface since the interface itself is ill-defined. This makes this test lessuseful than it otherwise might be.
Example: Build a dictionary that maps the ordinals from0 to255 totheir character equivalents.
>>>d={}>>>keys=range(256)>>>vals=map(chr,keys)>>>map(operator.setitem,[d]*len(keys),keys,vals)# doctest: +SKIP
Theoperator module also defines tools for generalized attribute and itemlookups. These are useful for making fast field extractors as arguments formap(),sorted(),itertools.groupby(), or other functions thatexpect a function argument.
Return a callable object that fetchesattr from its operand. If more than oneattribute is requested, returns a tuple of attributes. After,f=attrgetter('name'), the callf(b) returnsb.name. After,f=attrgetter('name','date'), the callf(b) returns(b.name,b.date).
The attribute names can also contain dots; afterf=attrgetter('date.month'),the callf(b) returnsb.date.month.
New in version 2.4.
Changed in version 2.5:Added support for multiple attributes.
Changed in version 2.6:Added support for dotted attributes.
Return a callable object that fetchesitem from its operand using theoperand’s__getitem__() method. If multiple items are specified,returns a tuple of lookup values. Equivalent to:
defitemgetter(*items):iflen(items)==1:item=items[0]defg(obj):returnobj[item]else:defg(obj):returntuple(obj[item]foriteminitems)returng
The items can be any type accepted by the operand’s__getitem__()method. Dictionaries accept any hashable value. Lists, tuples, andstrings accept an index or a slice:
>>>itemgetter(1)('ABCDEFG')'B'>>>itemgetter(1,3,5)('ABCDEFG')('B', 'D', 'F')>>>itemgetter(slice(2,None))('ABCDEFG')'CDEFG'
New in version 2.4.
Changed in version 2.5:Added support for multiple item extraction.
Example of usingitemgetter() to retrieve specific fields from atuple record:
>>>inventory=[('apple',3),('banana',2),('pear',5),('orange',1)]>>>getcount=itemgetter(1)>>>map(getcount,inventory)[3, 2, 5, 1]>>>sorted(inventory,key=getcount)[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Return a callable object that calls the methodname on its operand. Ifadditional arguments and/or keyword arguments are given, they will be givento the method as well. Afterf=methodcaller('name'), the callf(b)returnsb.name(). Afterf=methodcaller('name','foo',bar=1), thecallf(b) returnsb.name('foo',bar=1).
New in version 2.6.
This table shows how abstract operations correspond to operator symbols in thePython syntax and the functions in theoperator module.
| Operation | Syntax | Function |
|---|---|---|
| Addition | a+b | add(a,b) |
| Concatenation | seq1+seq2 | concat(seq1,seq2) |
| Containment Test | objinseq | contains(seq,obj) |
| Division | a/b | div(a,b) (without__future__.division) |
| Division | a/b | truediv(a,b) (with__future__.division) |
| Division | a//b | floordiv(a,b) |
| Bitwise And | a&b | and_(a,b) |
| Bitwise Exclusive Or | a^b | xor(a,b) |
| Bitwise Inversion | ~a | invert(a) |
| Bitwise Or | a|b | or_(a,b) |
| Exponentiation | a**b | pow(a,b) |
| Identity | aisb | is_(a,b) |
| Identity | aisnotb | is_not(a,b) |
| Indexed Assignment | obj[k]=v | setitem(obj,k,v) |
| Indexed Deletion | delobj[k] | delitem(obj,k) |
| Indexing | obj[k] | getitem(obj,k) |
| Left Shift | a<<b | lshift(a,b) |
| Modulo | a%b | mod(a,b) |
| Multiplication | a*b | mul(a,b) |
| Negation (Arithmetic) | -a | neg(a) |
| Negation (Logical) | nota | not_(a) |
| Right Shift | a>>b | rshift(a,b) |
| Sequence Repetition | seq*i | repeat(seq,i) |
| Slice Assignment | seq[i:j]=values | setslice(seq,i,j,values) |
| Slice Deletion | delseq[i:j] | delslice(seq,i,j) |
| Slicing | seq[i:j] | getslice(seq,i,j) |
| String Formatting | s%obj | mod(s,obj) |
| Subtraction | a-b | sub(a,b) |
| Truth Test | obj | truth(obj) |
| Ordering | a<b | lt(a,b) |
| Ordering | a<=b | le(a,b) |
| Equality | a==b | eq(a,b) |
| Difference | a!=b | ne(a,b) |
| Ordering | a>=b | ge(a,b) |
| Ordering | a>b | gt(a,b) |