liveBook · Manning

Operator module

As explained in Python Workout: 50 ten-minute exercises

The operator module is a Python standard-library module providing function equivalents for many built-in operators.

The operator module supplies function equivalents for Python operators, letting a program select an operation as data instead of branching through an if statement. section 6.6 section 6.7

A prefix calculator can split an input such as `+ 2 3`, convert its operands, and dispatch through a dictionary keyed by `+`, `-`, `*`, `/`, `**`, or `%`. section 6.6 section 6.7

Sorting records with itemgetter

`operator.itemgetter('last', 'first')` creates a key function that retrieves both dictionary values, allowing `sorted(people, key=itemgetter('last', 'first'))` without a one-off function or lambda. section 3.12

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

Browse a complete calculator implementation: define one function per operation, map operator strings to functions, unpack the input, convert operands, and invoke the selected function. section 6.7

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Works through calculator dispatch and itemgetter usage, but does not enumerate the module’s full API.
Examples
Demonstrates a prefix arithmetic calculator and sorting dictionaries by last name and first name.
What it assumes
Assumes familiarity with functions, dictionaries, unpacking, string splitting, and sorting while reinforcing their combined use.
What you can do after
Apply it via Python’s standard library to build dispatch tables and concise sorting key functions.
How it connects
Connects operator functions with functions, dictionaries, dispatch tables, lambda expressions, string splitting, and sorting.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.