liveBook · Manning

Operator module

As explained in Python Workout, Second Edition

The operator module is a Python standard-library module that provides function forms of built-in operators and related operations.

Use the operator module when an operation needs to become a function. Its itemgetter function is especially useful as a sorting key: itemgetter('name') returns a function that retrieves the name value from each dictionary. section 4.11

Two practical patterns make the module useful:

  • Replace a one-use named function or less-readable lambda with itemgetter when sorting records by one or more keys. section 4.11
  • Build a dispatch table by storing operator functions as dictionary values, then select and call the function associated with an input symbol. section 7.7
  • Handle structured input deliberately: unpack the result of split(), and use maxsplit when unrestricted splitting could produce too many values. section 7.7

Sort dictionaries without a custom key function

from operator import itemgetter for person in sorted(people, key=itemgetter('name')): print(person) Pass multiple keys to sort hierarchically: itemgetter('size', 'name') sorts by size first and name second. section 4.11

def add(a,b):
    return a + b

def sub(a,b):
    return a - b

def mul(a,b):
    return a * b

def div(a,b):
    return a / b

def pow(a,b):
    return a ** b

def mod(a,b):
    return a % b

def calc(to_solve):
    operations = {'+' : add,     #1
                  '-' : sub,
                  '*' : mul,
                  '/' : div,
                  '**' : pow,
                  '%' : mod}

    op, first_s, second_s = to_solve.split()    #2
    first = int(first_s)                      #3
    second = int(second_s)

    return operations[op](first, second)     #4

Inspect a complete calculator pattern that maps symbols such as + and ** to functions, parses three input fields, and invokes the selected operation. section 7.7

How Python Workout, Second Edition covers it

How deep it goes
Explains itemgetter construction, multi-key sorting, dispatch-table lookup, unpacking, and maxsplit, but not module-wide API coverage.
Examples
Uses country dictionaries, sorted people records, tuple and string indexing, and a calculator dispatch table.
What it assumes
Assumes familiarity with functions, dictionaries, sorting, string splitting, and tuple unpacking.
What you can do after
Apply it via itemgetter and operator-function dictionaries to write concise sorting keys and dispatch-driven calculations.
How it connects
Connects itemgetter with sorting, key functions, lambda expressions, dictionaries, dispatch tables, string splitting, and unpacking.

Also explained in

Compare how 2 books explain operator module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.