The dispatch function is a general method for implementing a message passing interface for abstract data. To implement message dispatch, we have thus far used conditional statements to compare the message string to a fixed set of known messages.

The built-in dictionary data type provides a general method for looking up a value for a key. Instead of using conditionals to implement dispatching, we can use dictionaries with string keys.

The mutable account data type below is implemented as a dictionary. It has a constructor account and selector check_balance, as well as functions to deposit or withdraw funds. Moreover, the local state of the account is stored in the dictionary alongside the functions that implement its behavior.

1def account(initial_balance):
2    def deposit(amount):
3        dispatch['balance'] += amount
4        return dispatch['balance']
5    def withdraw(amount):
6        if amount > dispatch['balance']:
7            return 'Insufficient funds'
8        dispatch['balance'] -= amount
9        return dispatch['balance']
10    dispatch = {'deposit':   deposit,
11                'withdraw':  withdraw,
12                'balance':   initial_balance}
13    return dispatch
14
15def withdraw(account, amount):
16    return account['withdraw'](amount)
17def deposit(account, amount):
18    return account['deposit'](amount)
19def check_balance(account):
20    return account['balance']
21
22a = account(20)
23deposit(a, 5)
24withdraw(a, 17)
25check_balance(a)
Step 13 of 28
line that has just executed

next line to execute

Global
account
 
withdraw
 
deposit
 
check_balance
 
a
 
f1: account [parent=Global]
initial_balance20
deposit
 
withdraw
 
dispatch
 
Return
value
 
func account(initial_balance) [parent=Global]
func withdraw(account, amount) [parent=Global]
func deposit(account, amount) [parent=Global]
func check_balance(account) [parent=Global]
func deposit(amount) [parent=f1]
func withdraw(amount) [parent=f1]
dict
"balance"20
"deposit"
 
"withdraw"
 

The name dispatch within the body of the account constructor is bound to a dictionary that contains the messages accepted by an account as keys. The balance is a number, while the messages deposit and withdraw are bound to functions. These functions have access to the dispatch dictionary, and so they can read and change the balance. By storing the balance in the dispatch dictionary rather than in the account frame directly, we avoid the need for nonlocal statements in deposit and withdraw.

The operators += and -= are shorthand in Python (and many other languages) for combined lookup and re-assignment. The last two lines below are equivalent.

>>> a = 2
>>> a = a + 1
>>> a += 1