Python Distilled 1st Edition - Ebook PDF Download
Python Distilled 1st Edition - Ebook PDF Download
download
https://ebooksecure.com/download/python-distilled-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-building-python-
programs-1st-edition/
http://ebooksecure.com/product/python-for-dummies-1st-edition-
pdf-version/
https://ebooksecure.com/download/problem-solving-and-python-
programming-ebook-pdf/
https://ebooksecure.com/download/programming-and-problem-solving-
with-python-ebook-pdf/
Data Structures & Algorithms in Python 1st Edition John
Canning - eBook PDF
https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf-2/
https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/
https://ebooksecure.com/download/r-and-python-for-oceanographers-
a-practical-guide-with-applications-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-
python-4th-edition/
http://ebooksecure.com/product/ebook-pdf-python-programming-in-
context-3rd-edition/
Python Distilled
This page intentionally left blank
Python Distilled
David M. Beazley
The author and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed
for incidental or consequential damages in connection with or arising out of the use of the information or
programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities (which may
include electronic versions; custom cover designs; and content particular to your business, training goals,
marketing focus, or branding interests), please contact our corporate sales department
at [email protected] or (800) 382-3419.
For questions about sales outside the U.S., please contact [email protected].
All rights reserved. This publication is protected by copyright, and permission must be obtained from the
publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or
by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the Pearson Education Global Rights &
Permissions Department, please visit www.pearson.com/permissions.
ISBN-13: 978-0-13-417327-6
ISBN-10: 0-13-417327-9
ScoutAutomatedPrintCode
Contents
Preface xiii
1 Python Basics 1
1.1 Running Python 1
1.2 Python Programs 2
1.3 Primitives, Variables, and
Expressions 3
1.4 Arithmetic Operators 5
1.5 Conditionals and Control Flow 7
1.6 Text Strings 9
1.7 File Input and Output 12
1.8 Lists 13
1.9 Tuples 15
1.10 Sets 17
1.11 Dictionaries 18
1.12 Iteration and Looping 21
1.13 Functions 22
1.14 Exceptions 24
1.15 Program Termination 26
1.16 Objects and Classes 26
1.17 Modules 30
1.18 Script Writing 32
1.19 Packages 33
1.20 Structuring an Application 34
1.21 Managing Third-Party Packages 35
1.22 Python: It Fits Your Brain 36
5 Functions 101
5.1 Function Definitions 101
5.2 Default Arguments 101
5.3 Variadic Arguments 102
5.4 Keyword Arguments 103
5.5 Variadic Keyword Arguments 104
5.6 Functions Accepting All Inputs 104
5.7 Positional-Only Arguments 105
5.8 Names, Documentation Strings, and Type
Hints 106
5.9 Function Application and Parameter
Passing 107
5.10 Return Values 109
5.11 Error Handling 110
5.12 Scoping Rules 111
5.13 Recursion 114
viii Contents
6 Generators 139
6.1 Generators and yield 139
6.2 Restartable Generators 142
6.3 Generator Delegation 142
6.4 Using Generators in Practice 144
6.5 Enhanced Generators and yield
Expressions 146
6.6 Applications of Enhanced
Generators 148
6.7 Generators and the Bridge to
Awaiting 151
6.8 Final Words: A Brief History of
Generators and Looking
Forward 152
Index 321
Preface
More than 20 years have passed since I authored the Python Essential Reference. At that time,
Python was a much smaller language and it came with a useful set of batteries in its
standard library. It was something that could mostly fit in your brain. The Essential Reference
reflected that era. It was a small book that you could take with you to write some Python
code on a desert island or inside a secret vault. Over the three subsequent revisions, the
Essential Reference stuck with this vision of being a compact but complete language
reference —because if you’re going to code in Python on vacation, why not use all of it?
Today, more than a decade since the publication of the last edition, the Python world is
much different. No longer a niche language, Python has become one of the most popular
programming languages in the world. Python programmers also have a wealth of
information at their fingertips in the form of advanced editors, IDEs, notebooks, web
pages, and more. In fact, there’s probably little need to consult a reference book when
almost any reference material you might want can be conjured to appear before your eyes
with the touch of a few keys.
If anything, the ease of information retrieval and the scale of the Python universe
presents a different kind of challenge. If you’re just starting to learn or need to solve a new
problem, it can be overwhelming to know where to begin. It can also be difficult to
separate the features of various tools from the core language itself. These kinds of problems
are the rationale for this book.
Python Distilled is a book about programming in Python. It’s not trying to document
everything that’s possible or has been done in Python. Its focus is on presenting a modern
yet curated (or distilled) core of the language. It has been informed by my years of teaching
Python to scientists, engineers, and software professionals. However, it’s also a product of
writing software libraries, pushing the edges of what makes Python tick, and finding out
what’s most useful.
For the most part, the book focuses on Python programming itself. This includes
abstraction techniques, program structure, data, functions, objects, modules, and so
forth— topics that will well serve programmers working on Python projects of any size.
Pure reference material that can be easily obtained via an IDE (such as lists of functions,
names of commands, arguments, etc.) is generally omitted. I’ve also made a conscious
choice to not describe the fast-changing world of Python tooling —editors, IDEs,
deployment, and related matters.
Perhaps controversially, I don’t generally focus on language features related to large-scale
software project management. Python is sometimes used for big and serious things—
comprised of millions upon millions of lines of code. Such applications require specialized
tooling, design, and features. They also involve committees, and meetings, and decisions
to be made about very important matters. All this is too much for this small book. But
xiv Preface
perhaps the honest answer is that I don’t use Python to write such applications— and
neither should you. At least not as a hobby.
In writing a book, there is always a cut-off for the ever-evolving language features. This
book was written during the era of Python 3.9. As such, it does not include some of the
major additions planned for later releases — for example, structural pattern matching.
That’s a topic for a different time and place.
Last, but not least, I think it’s important that programming remains fun. I hope that my
book will not only help you become a productive Python programmer but also capture
some of the magic that has inspired people to use Python for exploring the stars, flying
helicopters on Mars, and spraying squirrels with a water cannon in the backyard.
Acknowledgments
I’d like to thank the technical reviewers, Shawn Brown, Sophie Tabac, and Pete Fein, for
their helpful comments. I’d also like to thank my long-time editor Debra Williams Cauley
for her work on this and past projects. The many students who have taken my classes have
had a major if indirect impact on the topics covered in this book. Last, but not least, I’d
like to thank Paula, Thomas, and Lewis for their support and love.
This chapter gives an overview of the core of the Python language. It covers variables,
data types, expressions, control flow, functions, classes, and input/output. The chapter
concludes with a discussion of modules, script writing, packages, and a few tips on
organizing larger programs. This chapter is not trying to provide comprehensive coverage
of every feature, nor does it concern itself with all of the tooling that might surround a
larger Python project. However, experienced programmers should be able to extrapolate
from the material here to write more advanced programs. Newcomers are encouraged to
try the examples in a simple environment, such as a terminal window and a basic text
editor.
Certain environments may display a different prompt. The following output is from
ipython (an alternate shell for Python):
In [2]:
Regardless of the exact form of output you see, the underlying principle is the same.
You type a command, it runs, and you immediately see the output.
Python’s interactive mode is one of its most useful features because you can type any
valid statement and immediately see the result. This is useful for debugging and
experimentation. Many people, including the author, use interactive Python as their
desktop calculator. For example:
>>> 6000 + 4523.50 + 134.25
10657.75
>>> _ + 8192.75
18850.5
>>>
When you use Python interactively, the variable _ holds the result of the last operation.
This is useful if you want to use that result in subsequent statements. This variable only
gets defined when working interactively, so don’t use it in saved programs.
You can exit the interactive interpreter by typing quit() or the EOF (end of file)
character. On UNIX, EOF is Ctrl+D; on Windows, it’s Ctrl+Z.
Python source files are UTF-8-encoded text files that normally have a .py suffix. The
# character denotes a comment that extends to the end of the line. International (Unicode)
characters can be freely used in the source code as long as you use the UTF-8 encoding
(this is the default in most editors, but it never hurts to check your editor settings if you’re
unsure).
1.3 Primitives, Variables, and Expressions 3
To execute the hello.py file, provide the filename to the interpreter as follows:
shell % python3 hello.py
Hello World
shell %
It is common to use #! to specify the interpreter on the first line of a program, like this:
#!/usr/bin/env python3
print('Hello World')
On UNIX, if you give this file execute permissions (for example, by chmod +x
hello.py), you can run the program by typing hello.py into your shell.
On Windows, you can double-click on a .py file or type the name of the program into
the Run command on the Windows Start menu to launch it. The #! line, if given, is used
to pick the interpreter version (Python 2 versus 3). Execution of a program might take
place in a console window that disappears immediately after the program completes—
often before you can read its output. For debugging, it’s better to run the program within
a Python development environment.
The interpreter runs statements in order until it reaches the end of the input file. At
that point, the program terminates and Python exits.
A variable is a name that refers to a value. A value represents an object of some type:
x = 42
Sometimes you might see a type explicitly attached to a name. For example:
x: int = 42
The type is merely a hint to improve code readability. It can be used by third-party
code-checking tools. Otherwise, it is completely ignored. It does not prevent you from
assigning a different kind of value later.
An expression is a combination of primitives, names, and operators that produces a
value:
2 + 3 * 4 # -> 14
4 Chapter 1 Python Basics
The while statement tests the conditional expression that immediately follows. If the
tested condition is true, the body of the while statement executes. The condition is
then retested and the body executed again until the condition becomes false. The body
of the loop is denoted by indentation. Thus, the three statements following while in
interest.py execute on each iteration. Python doesn’t specify the amount of required
indentation, as long as it’s consistent within a block. It is most common to use four spaces
per indentation level.
One problem with the interest.py program is that the output isn’t very pretty. To
make it better, you could right-align the columns and limit the precision of principal
to two digits. Change the print() function to use a so-called f-string like this:
print(f'{year:>3d} {principal:0.2f}')
In the f-string, variable names and expressions can be evaluated by enclosing them in
curly braces. Optionally, each substitution can have a formatting specifier attached to it.
'>3d' means a three-digit decimal number, right aligned. '0.2f' means a floating-point
number with two decimal places of accuracy. More information about these formatting
codes can be found in Chapter 9.
Now the output of the program looks like this:
1 1050.00
2 1102.50
3 1157.62
4 1215.51
5 1276.28
1.4 Arithmetic Operators 5
Operation Description
x + y Addition
x - y Subtraction
x * y Multiplication
x / y Division
x // y Truncating division
x ** y Power (x to the y power)
x % y Modulo (x mod y). Remainder.
–x Unary minus
+x Unary plus
The division operator (/) produces a floating-point number when applied to integers.
Therefore, 7/4 is 1.75. The truncating division operator //, also known as floor division,
truncates the result to an integer and works with both integers and floating-point
numbers. The modulo operator returns the remainder of the division x // y. For
example, 7 % 4 is 3. For floating-point numbers, the modulo operator returns the
floating-point remainder of x // y, which is x – (x // y) * y.
In addition, the built-in functions in Table 1.2 provide a few more commonly used
numerical operations.
The round() function implements “banker’s rounding.” If the value being rounded is
equally close to two multiples, it is rounded to the nearest even multiple (for example, 0.5
is rounded to 0.0, and 1.5 is rounded to 2.0).
Integers provide a few additional operators to support bit manipulation, shown in
Table 1.3.
6 Chapter 1 Python Basics
Operation Description
One would commonly use these with binary integers. For example:
a = 0b11001001
mask = 0b11110000
x = (a & mask) >> 4 # x = 0b1100 (12)
In this example, 0b11001001 is how you write an integer value in binary. You could
have written it as decimal 201 or hexadecimal 0xc9, but if you’re fiddling with bits, binary
makes it easier to visualize what you’re doing.
The semantics of the bitwise operators assumes that the integers use a two’s
complement binary representation and that the sign bit is infinitely extended to the left.
Some care is required if you are working with raw bit patterns that are intended to map to
native integers on the hardware. This is because Python does not truncate the bits or allow
values to overflow — instead, the result will grow arbitrarily large in magnitude. It’s up to
you to make sure the result is properly sized or truncated if needed.
To compare numbers, use the comparison operators in Table 1.4.
Operation Description
x == y Equal to
x != y Not equal to
x < y Less than
x > y Greater than
x >= y Greater than or equal to
x <= y Less than or equal to
Operator Description
For these, you can write the following shortened operation instead:
x += 1
y *= n
This shortened form of update can be used with any of the +, -, *, **, /, //, %, &, |, ^,
<<, >>operators. Python does not have increment (++) or decrement (--) operators found
in some other languages.
The bodies of the if and else clauses are denoted by indentation. The else clause is
optional. To create an empty clause, use the pass statement, as follows:
if a < b:
pass # Do nothing
else:
print('Computer says No')
If you are assigning a value in combination with a test, use a conditional expression:
maxval = a if a > b else b
Sometimes, you may see the assignment of a variable and a conditional combined
together using the := operator. This is known as an assignment expression (or more
colloquially as the “walrus operator” because := looks like a walrus tipped over on its
side —presumably playing dead). For example:
x = 0
while (x := x + 1) < 10: # Prints 1, 2, 3, ..., 9
print(x)
print('Done')
The continue statement skips the rest of the loop body and goes back to the top of the
loop. For example:
x = 0
while x < 10:
x += 1
if x == 5:
continue # Skips the print(x). Goes back to loop start.
print(x)
print('Done')
1.6 Text Strings 9
a = 'Hello World'
b = "Python is groovy"
c = '''Computer says no.'''
d = """Computer still says no."""
The same type of quote used to start a string must be used to terminate it. Triple-
quoted strings capture all the text until the terminating triple quote — as opposed to single-
and double-quoted strings which must be specified on one logical line. Triple-quoted
strings are useful when the contents of a string literal span multiple lines of text:
print('''Content-type: text/html
Immediately adjacent string literals are concatenated into a single string. Thus, the
above example could also be written as:
print(
'Content-type: text/html\n'
'\n'
'<h1> Hello World </h1>\n'
'Clock <a href="http://www.python.org">here</a>\n'
)
Although this is only using simple variable names, any valid expression can appear. For
example:
base_year = 2020
...
print(f'{base_year + year:>4d} {principal:0.2f}')
As an alternative to f-strings, the format() method and % operator are also sometimes
used to format strings. For example:
print('{0:>3d} {1:0.2f}'.format(year, principal))
print('%3d %0.2f' % (year, principal))
10 Chapter 1 Python Basics
To extract a substring, use the slicing operator s[i:j]. It extracts all characters from s
whose index k is in the range i <= k < j. If either index is omitted, the beginning or end
of the string is assumed, respectively:
c = a[:5] # c = 'Hello'
d = a[6:] # d = 'World'
e = a[3:8] # e = 'lo Wo'
f = a[-5:] # f = 'World'
Strings have a variety of methods for manipulating their contents. For example, the
replace() method performs a simple text replacement:
g = a.replace('Hello', 'Hello Cruel') # f = 'Hello Cruel World'
Table 1.6 shows a few common string methods. Here and elsewhere, arguments
enclosed in square brackets are optional.
Method Description
Python never implicitly interprets the contents of a string as numerical data. Thus, +
always concatenates strings:
x = '37'
y = '42'
z = x + y # z = '3742' (String Concatenation)
Non-string values can be converted into a string representation by using the str(),
repr(),or format() functions. Here’s an example:
s = 'The value of x is ' + str(x)
s = 'The value of x is ' + repr(x)
s = 'The value of x is ' + format(x, '4d')
Although str() and repr() both create strings, their output is often different. str()
produces the output that you get when you use the print() function, whereas repr()
creates a string that you type into a program to exactly represent the value of an object.
For example:
>>> s = 'hello\nworld'
>>> print(str(s))
hello
world
>>> print(repr(s))
'hello\nworld'
>>>
When debugging, use repr(s) to produce output because it shows you more
information about a value and its type.
The format() function is used to convert a single value to a string with a specific
formatting applied. For example:
>>> x = 12.34567
>>> format(x, '0.2f')
'12.35'
>>>
The format code given to format() is the same code you would use with f-strings
when producing formatted output. For example, the above code could be replaced by the
following:
>>> f'{x:0.2f}'
'12.35'
>>>
12 Chapter 1 Python Basics
The open() function returns a new file object. The with statement that precedes it
declares a block of statements (or context) where the file (file) is going to be used. Once
control leaves this block, the file is automatically closed. If you don’t use the with
statement, the code would need to look like this:
file = open('data.txt')
for line in file:
print(line, end='') # end='' omits the extra newline
file.close()
It’s easy to forget the extra step of calling close() so it’s better to use the with
statement and have the file closed for you.
The for loop iterates line-by-line over the file until no more data is available.
If you want to read the file in its entirety as a string, use the read() method like this:
with open('data.txt') as file:
data = file.read()
If you want to read a large file in chunks, give a size hint to the read() method as
follows:
with open('data.txt') as file:
while (chunk := file.read(10000)):
print(chunk, end='')
The := operator used in this example assigns to a variable and returns its value so that it
can be tested by the while loop to break out. When the end of a file is reached, read()
returns an empty string. An alternate way to write the above function is using break:
with open('data.txt') as file:
while True:
chunk = file.read(10000)
if not chunk:
break
print(chunk, end='')
To make the output of a program go to a file, supply a file argument to the print()
function:
with open('out.txt', 'wt') as out:
while year <= numyears:
1.8 Lists 13
In addition, file objects support a write() method that can be used to write string data.
For example, the print() function in the previous example could have been written
this way:
out.write(f'{year:3d} {principal:0.2f}\n')
By default, files contain text encoded as UTF-8. If you’re working with a different text
encoding, use the extra encoding argument when opening the file. For example:
with open('data.txt', encoding='latin-1') as file:
data = file.read()
Sometimes you might want to read data typed interactively in the console. To do that,
use the input() function. For example:
name = input('Enter your name : ')
print('Hello', name)
The input() function returns all of the typed text up to the terminating newline,
which is not included.
1.8 Lists
Lists are an ordered collection of arbitrary objects. Create a list by enclosing values in
square brackets:
names = [ 'Dave', 'Paula', 'Thomas', 'Lewis' ]
Lists are indexed by integers, starting with zero. Use the indexing operator to access and
modify individual items of the list:
a = names[2] # Returns the third item of the list, 'Thomas'
names[2] = 'Tom' # Changes the third item to 'Tom'
print(names[-1]) # Print the last item ('Lewis')
To append new items to the end of a list, use the append() method:
names.append('Alex')
To insert an item in the list at a specific position, use the insert() method:
names.insert(2, 'Aya')
You can extract or reassign a portion of a list by using the slicing operator:
b = names[0:2] # b -> ['Dave', 'Paula']
c = names[2:] # c -> ['Aya', 'Tom', 'Lewis', 'Alex']
names[1] = 'Becky' # Replaces 'Paula' with 'Becky'
names[0:2] = ['Dave', 'Mark', 'Jeff'] # Replace the first two items
# with ['Dave','Mark','Jeff']
Specifying [] for an empty list is more idiomatic. list is the name of the class
associated with the list type. It’s more common to see it used when performing
conversions of data to a list. For example:
letters = list('Dave') # letters = ['D', 'a', 'v', 'e']
Most of the time, all of the items in a list are of the same type (for example, a list of
numbers or a list of strings). However, lists can contain any mix of Python objects,
including other lists, as in the following example:
a = [1, 'Dave', 3.14, ['Mark', 7, 9, [100, 101]], 10]
Items contained in nested lists are accessed by applying more than one indexing
operation:
a[1] # Returns 'Dave'
a[3][2] # Returns 9
a[3][3][1] # Returns 101
The following program pcost.py illustrates how to read data into a list and perform a
simple calculation. In this example, lines are assumed to contain comma-separated values.
The program computes the sum of the product of two columns.
# pcost.py
#
# Reads input lines of the form 'NAME,SHARES,PRICE'.
# For example:
#
# SYM,123,456.78
1.9 Tuples 15
import sys
if len(sys.argv) != 2:
raise SystemExit(f'Usage: {sys.argv[0]} filename')
rows = []
with open(sys.argv[1], 'rt') as file:
for line in file:
rows.append(line.split(','))
The first line of this program uses the import statement to load the sys module from
the Python library. This module is used to obtain command-line arguments which are
found in the list sys.argv. The initial check makes sure that a filename has been provided.
If not, a SystemExit exception is raised with a helpful error message. In this message,
sys.argv[0] inserts the name of the program that’s running.
The open() function uses the filename that was specified on the command line. The
for line in file loop is reading the file line by line. Each line is split into a small list
using the comma character as a delimiter. This list is appended to rows. The final result,
rows, is a list of lists —remember that a list can contain anything including other lists.
The expression [ int(row[1]) * float(row[2]) for row in rows ] constructs a new
list by looping over all of the lists in rows and computing the product of the second and
third items. This useful technique for constructing a list is known as a list comprehension.
The same computation could have been expressed more verbosely as follows:
values = []
for row in rows:
values.append(int(row[1]) * float(row[2]))
total = sum(values)
As a general rule, list comprehensions are a preferred technique for performing simple
calculations. The built-in sum() function computes the sum for all items in a sequence.
1.9 Tuples
To create simple data structures, you can pack a collection of values into an immutable
object known as a tuple. You create a tuple by enclosing a group of values in parentheses:
Another Random Scribd Document
with Unrelated Content
“They take a bulrush, and take the skin off from each side down
to the white pith, leaving a little strip of skin on the edge to stiffen it,
and make it stand up,—that is for a wick; then they dip it a few
times in melted tallow, and make a light of it; but it’s a little,
miserable light.”
“There’s but very few of them can read. They don’t have schools,
as they do here: and the poor people can’t send their children, for so
soon as a child is big enough to open a gate, or turn a wheel, or
mind another child, run of errands, hold a horse, or scare the rooks
and the birds from the grain, they are obliged to put that child to
work, in order to live and pay rent.
“Women in England spin twine and make lines with a large wheel,
which a little boy turns; and when the little boy gets tired, the
woman sings to him, to cheer him up,—
And the little boy will brighten up, and make the wheel fly, because
he’s going to leave off when he’s done.“
“You are a little boy, Charlie,” said Sally, who was listening with
great attention, “to know so much about the affairs of older people.”
“Ah, mother, misery makes boys sharp to learn. If you was a little
boy, and your mother had but one cow, and she churned, and you
asked her for a little piece of butter, and she said, with the tear in
her eye, ‘No, my child, it must go to pay the rent;’ if you brought in
a whole hat full of eggs, and had not eaten an egg for a year, and
should long for one, O, so much, and cry, and say, ‘O, mother, do
give me just one egg!’ and she said, ‘No, my child, they must all be
sold, for we are behindhand with the rent;’ you would know what
paying rent means.”
“Well, Charlie, you shall have all the butter you want every time I
churn; and I’ll spread your bread both sides, and on the edges.”
“It wouldn’t be a very safe place for me to go,” said Joe, “for I’ve
the blood of a great many trees on my conscience.”
“They raise trees there from the seed, and plant and set out
thousands of acres. O, I wish you could only be in the fens in
picking-time, I guess you would laugh.”
“An old woman, with her black face all tanned up (for the women
work in the fields there), looks so funny peeping out of a great heap
of white feathers and down! and then such an awful squawking as
so many fowl make! Don’t you have any lords and dukes here,
father?”
“Who is Uncle Isaac’s, and Captain Rhines’s, and the rest of the
folks round here?”
“Yes; as long as they live; and then they can sell it or leave it to
their children, or give it to whom they have a mind to.”
“O,” cried Charlie, jumping up, and reddening with excitement,
“how my poor father and mother would have worked, if they could
have thought they could ever have come to own land for
themselves! According to that, all that the people here do on the
land they do for themselves, and they are their own landlords.”
“Only think, to own your land, and have no rent to pay! I should
think it was just the country for poor people to live in.”
“I’m glad you told me all these things, father. I mean to do all I
can to help you and mother pay for the land, and by and by,
perhaps, when I get to be a man, I can have a piece of land.”
“I’ll tell you what you can do, Charles. Make baskets in the
evenings and rainy days, and sell them. I will let you have all you
get for them.”
“I thank you, father. I could make the house full before spring.”
“I,” said Joe, “when I am not too tired, will pound some of the
basket-stuff for you. It is hard work for a boy like you.”
“So will I,” said Ben. “I can pound enough in one evening to last
you a month.”
“Yes,” said Joe; “you and John might form a company, and go into
the basket business—Rhines & Bell. No; the Rhines Brothers; John
and you are brothers. John could pound the basket-stuff at home,
and bring it over here; you could make them, and he could sell them
to the fishermen in the summer. They use lots of baskets. If you sell
them to the store you won’t get any money, only goods; but the
fishermen will pay the cash.”
“Won’t that be nice! I tell you the very first thing I mean to have;
I’ll swap some baskets at the store, and get some cloth to make a
sail for my boat.”
“And I,” said Ben, “will rope it for you (sew a piece of rope around
the edge), and show you how to make the grummet-holes.”
“Then the next thing I’ll do, will be to get some powder, and,
when the birds come in the spring, I will learn to shoot and kill
them, and have feathers to sell, to help pay for the island.”
“If,” said Joe, “you don’t learn to shoot till the birds come, by the
time you get learned the thickest of them will all be gone. You ought
to fire at a mark this winter, and practise, and then when the birds
come you will not have so much to do.”
“I can’t get any powder till I sell my baskets; powder and shot
cost a good deal.”
“I’ll advance you the money, so that you can get a little powder
and shot. You can use peas and little stones part of the time: they
will go wild, but it will help you to get used to hearing a gun go off,
and learning to take sight, and hold her steady. Our folks will want
some baskets in the spring, and when I get through I will take them;
but I will let you have the money now.”
“Thank you a thousand times! What a good country this is, and
how good everybody is!” said the happy boy. “Everybody seems to
want to help me; it ain’t so in England.”
“That is because you are a good boy, and try to help yourself and
others.”
“There’s one other thing I must have, because I want it to make
baskets—that is a knife.”
“Then I’ll have some bits, and a bit-stock, and a fine-toothed saw.
O, if I only had the tools, wouldn’t I make things for mother! I’d
make a front door, and ceil up the kitchen, and cover up the
chimney, and make a closet, and a mantelpiece, and finish off a
bedroom for father and mother, and shingle the roof.”
“Well, Charlie,” said Ben, “you’ve laid out work enough for five or
six years. You had better go to bed now, and all the rest of us, for it
is past ten o’clock. I am sure I don’t know where this evening has
gone to.”
CHAPTER IX.
The next morning Charles went to look at the willows. He said they
were different from the sallies they made baskets of; that the same
kind grew in England, but they called them wild sallies there, and
never made baskets of them; but he thought if they could be made
to grow straight he could make a basket of them. So he got the axe,
and cut off a whole parcel of them, in order that they might sprout
up the next spring and grow straight.
“Father,” said Charles, “you never got all this powder and shot with
the money I gave you.”
“John told me that he would like very much to go into the basket
business with you, and would pound a lot of basket-stuff, and make
it all of a width, and trim the edges smooth and handsome, and get
out the rims and handles. He wants to know if you are willing to take
Fred Williams into partnership with you and him, because he wants
to go in. His father is a miller, and he can sell a good many baskets
to folks that come to the mill. Nova Scotia people often come there
after corn, and he could sell them to them, to sell again to the
fishermen down their way.”
“John Strout is going to the West Indies this winter, and will bring
the Perseverance over here, and leave her, because she’ll be safe.
John will send basket-stuff over by him, and you can send back word
whether you will take Williams into partnership.”
“I don’t know what would have become of me, if you and mother
had not taken me in. Now, John told me all about Fred. He said that
he didn’t want him to go with him and Uncle Isaac, because he knew
that they should have so much better time together; but he said one
day, when they were off together in a boat, Uncle Isaac told him
that we ought to deny ourselves to help others, and talked to him in
such a way that he felt ashamed of himself, and couldn’t look Uncle
Isaac in the face, but had to look right down in the bottom of the
boat. Since that he had gone with Fred, and was right glad of it, for
he had become a real good boy, and he’s as smart as lightning. I
saw that the day I was over to see John.”
“He has become a first-rate boy. Everybody that goes to the mill
says there is not a better, more obliging boy in town; and they are
always glad when he is in the mill, his father is so cross.”
“Do you know, father, it seems to me just like this about Fred.
When I get out an ash rim for a basket, it is hard work to bend it;
and if, after I have bent it, I don’t fasten it, but throw it down on the
floor and leave it, in the morning it will be straightened out just
where it was before; but if I fasten it till it gets dry and set, it will
stay so; and I think we ought to do all we can to keep Fred good till
he gets fairly set in good ways, and then he’ll stay set.”
Ben had scarcely removed the provisions from the canoe, and put
it all under cover, when the weather suddenly changed. As night
came on, the wind increased, with snow; and afterwards hauling to
the south-east, blew a hurricane, the rain falling in torrents through
the night; but at daylight hauled to the south-west, when it became
fair.
Ben and Joe were at work in the front room making shingles. At
morning high-water they heard a constant thumping in the direction
of the White Bull for more than an hour, when it gradually ceased. At
night they heard it again.
“Joe,” said Ben, “let us take the canoe after supper, and go over
and see what that thumping is. It is not the surf, nor rocks grinding
on each other, I know.”
When they reached the spot they found the bowsprit of a vessel,
with the bobstays hanging to it, having been broken off at the
gammoning, with the gripe attached to it. There was also the fore-
mast and fore-topmast, with the yards and head-stays, the mast
being carried away at the deck. The chain-plates also on the
starboard side and channels had been torn out, and hung to the
shrouds by the lanyards. On the port side there were only the
shrouds and the upper dead-eyes. The sails were on the yards, while
braces, clew-garnets, clew-lines, leach-lines, bunt-lines, and reef-
tackles,—some nearly of their entire length, others cut and parted,—
were rolled around the spars, and matted with kelps and eel-grass,
in almost inextricable confusion. In the fore-top was a chest lashed
fast, and filled with studding-sail gear, which having been fastened,
the rigging remained in it. These ropes were very long, and had
been but little worn.
“Well,” said Ben, looking upon the mass with that peculiar interest
that a wreck always inspires in the heart of a seaman, “I am sorry
for the poor fellows who have met with a misfortune; but this
rigging, these sails and iron-work, are a most precious God-send to
me.”
Iron and cordage were both very valuable articles in the country
at that time, as the British government had forbidden the erection of
rolling and slitting mills before the Revolution, and the manufactures
of the country were just struggling into life. Withes of wood were
used in lieu of ropes and chains.
“The long bolts in that gripe,” said Joe, “will make you a crane. A
few more links put to the chain on that bobstay will make you a first-
rate draught chain. The straps of the dead-eyes welded together,
and a little steel put on the point, will make a good crowbar.”
But Ben had ideas, which he did not make known to Joe, very
different from the construction of cranes or crowbars. These it were
which occasioned his joy at the sight of the wreck.
“These are the spars of a big ship,” said Ben; “neither the sea nor
the wind took these sticks out of her.”
“Because, if the ship had gone ashore, and gone to pieces, the
spars and this gripe would have gone where she did. She never lost
that mast by the wind. If she had, the chain-plates wouldn’t be
hanging to the shrouds, for no rigging would hold to tear the
channels from a ship’s side.”
“No more it wouldn’t. I never thought of that; but how did she
lose it?”
“She has run full splinter on to an iceberg, and struck it with her
starboard bow. An iceberg would scrub her chain off as easy as you
would pull a mitten off your hand.”
“Perhaps not. I’ve seen a vessel keep up, and get into port, that
had her stem cut off within four inches of the hood ends. Look
there,” pointing to the larboard shrouds of the fore-rigging; on the
dead-eyes and the shrouds were the marks of an axe. “Somebody
did that in cutting the lanyard to let the spars go clear of the ship.
They would not have done that if she had been going down.”
They built a shed of boards to put the rigging and sails under, and
yards, while Charles burnt the mast, bowsprit, and caps to get the
iron.
Snow having now fallen, they began to haul their spars and logs
to the beach. John Strout now came over and brought the basket-
stuff, and Charles sent word by him to John that he would like to
take Fred Williams into partnership.
John brought word that Fred’s father was going to repair the mill,
and that while that was going on, Fred would like to come over and
see Charles, and learn to make baskets. Charles sent word back that
it would be agreeable to him to have him come. He was now quite
excited. Here was company coming, and nowhere for them to sleep
but on the floor. There were but two bedsteads in the house,—one
in the kitchen, where Ben and his wife slept, and the other in the
front room, where Joe slept. This was the spare bed, and the best
room, though it was made a workshop of, and was half full of
shingles and staves; but they could do no better.
“I should not care for him,” said she; “I should as lief he would
sleep on the floor as not. If you give him as good as you have
yourself, that is good enough.”
“But, mother, I shouldn’t want him to go home and say that he
came to see me, and had to sleep on the floor; besides, John might
hear of it, and then he wouldn’t like to come.”
“O, no, mother! I’m afraid he won’t like it; and then he will play
some trick on us. I have thought of a plan, mother.”
“There are some yellow-birch joist up chamber, all curly, with real
handsome whorls in them. I think I could make a bedstead of them;
and then, you know, it would be my own, and we should have it if
any company came. I have got an auger that I borrowed of Uncle
Isaac, to bore the holes for the cord, and the earings on the sails
that came ashore would make a nice cord.”
“But I don’t like to ask father for the wood. He has saved it to
make something, and perhaps I might spoil it, and not make a
bedstead after all.”
“Ask him yourself. I’ll risk your spoiling the stuff. If you do, there’s
plenty more where that came from.”
Charlie asked for and obtained the joist. As he didn’t want Joe to
look at and criticise him, when he saw him coming from the woods
to his meals, he put it up chamber. At length he finished making it.
Then he scraped it with a scraper made of a piece of saw-plate, and
then rubbed it with dogfish skin, which made all the curls and veins
in the wood to show, and put it in the front room for Ben and Joe to
see when they came in to dinner.
“If I only had,” said Charles, “some dye-stuff, how handsome I
could make this look!”
Joe told him there was a little red ochre in the schooner, which he
would get for him. This Charles mixed with vinegar, and rubbed a
little on the wood, which brought out the beauty of the wood, and
gave it a nice color.
“If I were you, Charlie,” said Ben, “I would have a sacking bottom
to your bed, instead of bare cords.”
“What is that?”
“Why, there is a piece of canvas that was torn from one of the
sails, take that, and make it almost large enough to fill up the
bedstead; then hem it, and make a row of eyelet-holes all around
the edges, and cord it tight into the bedstead. It will be first rate to
sleep on.”
Fred now came over, and Charles taught him to set up and make a
basket. He made a good many, and burnt them up in the fire, till at
length he made one that would do. After this he got along very well.
The two boys now began to fire at a mark, as Fred had brought
some powder and shot, and a gun with him. Charles, at first, shut
up both eyes when he fired, and almost dropped the gun when it
went off, and was afraid it would kick; and Fred could show him as
much about shooting as he could Fred about basket-making; but he
soon got so that he could fire without winking, and hold the gun firm
to his shoulder, and hit a mark quite well. Then they took a block of
wood, and made it in the shape of a Whistler, and anchored it in the
water, and fired at that, as it was bobbing up and down in the water;
and at length Charles got so he could hit that twice out of four
times. When they had expended their ammunition, they took,
instead of shot, peas and gravel-stones.
One day, after dinner, Charles came running into the house all out
of breath, saying there was a little child in the woods.
“I have seen its tracks and its bare foot-prints in the snow. O,
father! do come and help me find it; it will freeze to death.”
“What is it?”
“It is a raccoon track thawed out; they look like a child’s track.”
“They are about twice as large as Sailor, and live in the woods on
mice, fish, and berries. I will show you one some day.”
They now began to take what Charles called real solid comfort.
The days were short; as Ben said, only two ends to them. They had
abundance of time to sleep, and were all in full health and vigor.
CHAPTER X.
One evening they made a rousing fire. Ben got out his shoemaker’s
bench, and was tapping a pair of shoes. Boots were not worn by
them; they wore shoes and buskins.
“Charlie,” said Joe, looking up from his work, “tell us some more
about England, like as you did the other night.”
“Yes, do, Charlie,” said Fred. “Was your father a cooper? You said
they made hoops of willow and alder.”
“A cruel, barbarous thing it is, too,” said Ben, “and ought to bring
a curse on any government.”
“They press sailors generally,” said Charles; “but when they are
very short of men they will take anybody they can get hold of. I have
heard say they couldn’t press a squire’s son, or a man that owned
land, and that they can’t go into a man’s house to take him; but, if
they catch him outside, or going into the door, they will take him.”
“What a bloody shame!” cried Ben, his face assuming that terrible
expression which Charles had seen on it when the encounter
between him and the land-pirates took place. “I wish I had been
there; I’d have given some of them sore heads. But they are not so
much to blame, after all. It is those that make the laws, and that set
the press-gang at work. I should like to wring their necks for them.”
“I shouldn’t think,” said Joe, “such men would fight very well for
the government that used them so.”
“They don’t,” said Ben; “and they dare not trust them; but they
scatter them through the ship, a few in every mess, and put them
where they can watch them. I was taken once by an English man-of-
war. They put a prize crew on board of us; part of them were
pressed men. We rose and retook her; the pressed men all joined
us, and went into our army.”
“I should have thought they would have gone into the privateers
or men-of-war.”
“They thought they were less likely to be taken again in the army,
for if the English had got hold of them, they would have hung them.
They told me that whenever they got into action with a French
vessel, they threw the shot overboard, if they could get a chance,
instead of putting it in the guns, in order that they might be taken;
and that they sometimes revenged themselves by shooting their
officers in the smoke and heat of the action.”
“I should think the officers would keep a bright look out for them.”
“So they do; and are very careful not to go under the tops, and
keep well clear of the masts, lest a marline-spike should come down
on their heads, or a block unhook, or a heaver fall, as accidents of
that kind were very apt to happen when pressed men were aloft. I
don’t believe a man could be so on his guard that I could not kill him
in the course of a three years’ cruise, if I wanted to, and appear to
do it by accident, too.
“I have seen hundreds of these men, and they all tell the same
story. I’ve seen a poor fellow who was pressed when he was
nineteen; his mother was a widow, and he was her sole
dependence. I’ve seen him, when he was telling me the story, jump
up and smite his hands together, while the tears ran down his
cheeks, and pray God to curse that government, and hope that he
might live to see its downfall; but I never heard them curse the
country; they seemed to love that; it was the government they
hated and cursed.”
“Was your father pressed when your uncle was?” said Joe.
“I don’t like to tell or think about it; but I will tell you. At the time
my uncle was taken, it made a great noise. People were very much
frightened, and kept very close, never going out in the evening if
they could help it.”
“I don’t see,” said Ben, “in a country where the law allowed them
to seize people in the street, and carry them off, why they could not
go into the house and take them.”
“Perhaps they could; but that was what folks said, that an
‘Englishman’s house was his castle,’ and they couldn’t come into the
house to take them, and they never did. We didn’t think they would
press my father, because he was neither a rope-maker nor
carpenter; but they were short of men, and all was fish that came to
their net. Nevertheless, we kept such strict watch that my father
would not have been taken; but he was sold to them by a blood-
seller.”
“A man that will go to the captain of the press-gang, and tell him
where he can find a man, and how he can get hold of him; and they
get paid for it.”
“O, that is the meanest, wickedest thing I ever did hear tell of.”
“It is often done in England, though; but this man didn’t do it for
money.”
“He and my father courted mother when they were both young
men; but she liked my father best, and married him. He always
hated my father after that; told lies about him, killed his geese, and
tried to injure him in his business. But when he found the press-
gang were about, he thought if he could sell him to them, and get
him out of the way, mother would marry him.”
“He must have been a fool, as well as a villain, to think a woman
would marry a man that did that.”
“But he did not think that would ever be known; but it came out.
He knew that my father had engaged to make cases for the army to
carry instruments in.”
“The blood-seller knew all about this, and told the press-gang. He
was in sight of the workshop, and hurrying on with all his might,
when four men jumped out from a hedge and seized him,—one of
whom put his hand on his shoulder, and told him he must go and
serve in the navy during his majesty’s pleasure. Before daylight he
was out of sight and hearing of everybody that knew him.”
“But how did you know what had become of him?” said Joe.
“He was going to board with his cousin, and come home Saturday
nights. They looked for him till the middle of the week, and, when
he didn’t come, his cousin came over to our house, and said to
mother, ‘Where is John? I thought he was going to work for the
army.’
“‘He went from here at three o’clock last Monday morning.’
“‘He has not been at our house, nor at the workshop, for I have
been to see.’
“Poor soul,” cried Sally, “how she must have suffered! Your cousin
ought to have broke it to her more gently. But what did you do
then?”
“He put her on the bed, and called some women that lived over
the way, and they brought her to. All her folks and friends came to
see her, and tried to comfort her, and told her that perhaps he had
gone on some unexpected business, and would return; and that
even if he was pressed, he might be discharged when the war was
over.”
“In about ten days my mother had a letter from him. It was all
blotted over with tears. He said he was on board the hulk at
Sheerness, and that if we came quick we could see him, as he might
be ordered away at any time.”
“It is an old man-of-war, not fit for service, and made a prison-ship
of, to keep the men in till they want them in the ships they are going
in. My grandfather went with us to the ship; there we found him
with two thousand more men.”
“O, my!” said Sally; “were all these poor men pressed?”
“No; my father said most of them were sailors who had shipped of
their own accord. He was so pale and heart-broken I should have
hardly known him. He wanted to be cheerful, and comfort us, but he
couldn’t. The tears ran down his cheeks in spite of him.
“He took my mother in his arms, and said, ‘My poor Nancy, what
will become of you and these little ones, now they have no father to
earn them bread, and keep want from the door; and poor old father,
too, that when we had food always had part of it.’ Little William, who
was just beginning to go alone, clung around his neck, and sobbed
as if his heart would break.
“‘We shall be at home, John, among friends; but you are going
among strangers into battle, to be exposed to the dangers of the
seas.’
“They now told us we must part, for we had been together two
hours, though it seemed to us but a few moments. We had to see
and talk with him right amongst a crowd of men: some were
swearing, some wrangling, and some laughing and talking, for the
sailors seemed to be as merry as could be, and in their rough way
tried to cheer us up. Father asked my grandfather to pray with him
before they parted; and when my father told some of the sailors
what he was going to do, they went among the rest, and it was so
still that you might have heard a pin drop. I saw tears in the eyes of
many of them when we went away, and they said, ‘God bless you,
old father!’ in a real hearty way, to my grandfather, and shook hands
with him.”
“Sailors are rough men,” said Ben, “for they live on a rough
element, and see rough usage; but there was not a sailor in all that
ship’s company would have betrayed his shipmate, as that blood-
seller did your father.”
“It was bitter parting. We never expected to see him again, and
we never did; for it was but a few months after that when he was
killed in battle.”
“What did your mother do,” said Ben, “when she heard that your
father was dead?”
“At first she took to her bed, and seemed quite heart-broken. After
a while she kind of revived up, and said it was her duty to take care
of us, for father’s sake. Then she hired men, and went into the shop
herself; and the neighbors and our relations helped us cut and
whiten the sallies, and pick the fowl, and we made out to pay the
rent, and were getting along very well, when there came a new
trouble.”
“Why, this same man, Robert Rankins, that sold my father, began
to come into the shop, and make us presents, and help us, and
finally asked my mother to marry him; but she spit in his face, and
called him a blood-seller, and told him what he had done to my
father; but still he would come; when, to be rid of him, she put the
children among my father’s folks, and took me and came to the
States; and the rest you know,” said the boy, his voice shaking with
the feelings which the recital called up.