100% found this document useful (2 votes)
437 views

Python Distilled 1st edition - eBook PDF instant download

The document provides links to various Python-related eBooks available for download, including titles like 'Python Distilled' and 'Python For Dummies.' It also includes information about the content structure of the book 'Python Distilled' by David M. Beazley, covering topics from Python basics to advanced programming concepts. Additionally, it mentions copyright information and contact details for sales inquiries.

Uploaded by

superthelelb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
437 views

Python Distilled 1st edition - eBook PDF instant download

The document provides links to various Python-related eBooks available for download, including titles like 'Python Distilled' and 'Python For Dummies.' It also includes information about the content structure of the book 'Python Distilled' by David M. Beazley, covering topics from Python basics to advanced programming concepts. Additionally, it mentions copyright information and contact details for sales inquiries.

Uploaded by

superthelelb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Python Distilled 1st edition - eBook PDF

download

https://ebookluna.com/download/python-distilled-ebook-pdf/

Download full version ebook from https://ebookluna.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookluna.com
to discover even more!

(eBook PDF) Building Python Programs 1st Edition

https://ebookluna.com/product/ebook-pdf-building-python-programs-1st-
edition/

Python For Dummies 1st Edition - PDF Version

https://ebookluna.com/product/python-for-dummies-1st-edition-pdf-version/

Problem Solving and Python Programming 1st edition - eBook PDF

https://ebookluna.com/download/problem-solving-and-python-programming-
ebook-pdf/

Programming and Problem Solving with Python 1st Edition - eBook PDF

https://ebookluna.com/download/programming-and-problem-solving-with-python-
ebook-pdf/
Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF

https://ebookluna.com/download/data-structures-algorithms-in-python-ebook-
pdf-2/

Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF

https://ebookluna.com/download/data-structures-algorithms-in-python-ebook-
pdf/

R and Python for Oceanographers: A Practical Guide with Applications 1st


Edition- eBook PDF

https://ebookluna.com/download/r-and-python-for-oceanographers-a-practical-
guide-with-applications-ebook-pdf/

(eBook PDF) Starting Out with Python (4th Edition)

https://ebookluna.com/product/ebook-pdf-starting-out-with-python-4th-
edition/

(eBook PDF) Python Programming in Context 3rd Edition

https://ebookluna.com/product/ebook-pdf-python-programming-in-context-3rd-
edition/
Python Distilled
This page intentionally left blank
Python Distilled

David M. Beazley

Boston • Columbus • New York • San Francisco • Amsterdam • Cape Town


Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
São Paulo • Sydney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark
claim, the designations have been printed with initial capital letters or in all capitals.

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 corpsales@pearsoned.com or (800) 382-3419.

For government sales inquiries, please contact governmentsales@pearsoned.com.

For questions about sales outside the U.S., please contact intlcs@pearson.com.

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2021943288

Copyright © 2022 Pearson Education, Inc.

Cover illustration by EHStockphoto/Shutterstock

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

2 Operators, Expressions, and Data


Manipulation 37
2.1 Literals 37
2.2 Expressions and Locations 38
2.3 Standard Operators 39
2.4 In-Place Assignment 41
2.5 Object Comparison 42
2.6 Ordered Comparison Operators 42
vi Contents

2.7 Boolean Expressions and Truth


Values 43
2.8 Conditional Expressions 44
2.9 Operations Involving Iterables 45
2.10 Operations on Sequences 47
2.11 Operations on Mutable
Sequences 49
2.12 Operations on Sets 50
2.13 Operations on Mappings 51
2.14 List, Set, and Dictionary
Comprehensions 52
2.15 Generator Expressions 54
2.16 The Attribute (.) Operator 56
2.17 The Function Call () Operator 56
2.18 Order of Evaluation 56
2.19 Final Words: The Secret Life of
Data 58

3 Program Structure and Control


Flow 59
3.1 Program Structure and
Execution 59
3.2 Conditional Execution 59
3.3 Loops and Iteration 60
3.4 Exceptions 64
3.4.1 The Exception
Hierarchy 67
3.4.2 Exceptions and Control
Flow 68
3.4.3 Defining New
Exceptions 69
3.4.4 Chained Exceptions 70
3.4.5 Exception
Tracebacks 73
3.4.6 Exception Handling
Advice 73
3.5 Context Managers and the with
Statement 75
3.6 Assertions and __debug__ 77
3.7 Final Words 78
Contents vii

4 Objects, Types, and Protocols 79


4.1 Essential Concepts 79
4.2 Object Identity and Type 80
4.3 Reference Counting and Garbage
Collection 81
4.4 References and Copies 83
4.5 Object Representation and Printing 84
4.6 First-Class Objects 85
4.7 Using None for Optional or Missing
Data 87
4.8 Object Protocols and Data
Abstraction 87
4.9 Object Protocol 89
4.10 Number Protocol 90
4.11 Comparison Protocol 92
4.12 Conversion Protocols 94
4.13 Container Protocol 95
4.14 Iteration Protocol 97
4.15 Attribute Protocol 98
4.16 Function Protocol 98
4.17 Context Manager Protocol 99
4.18 Final Words: On Being Pythonic 99

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

5.14 The lambda Expression 114


5.15 Higher-Order Functions 115
5.16 Argument Passing in Callback
Functions 118
5.17 Returning Results from
Callbacks 121
5.18 Decorators 124
5.19 Map, Filter, and Reduce 127
5.20 Function Introspection, Attributes,
and Signatures 129
5.21 Environment Inspection 131
5.22 Dynamic Code Execution and
Creation 133
5.23 Asynchronous Functions and
await 135
5.24 Final Words: Thoughts on Functions
and Composition 137

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

7 Classes and Object-Oriented


Programming 153
7.1 Objects 153
7.2 The class Statement 154
7.3 Instances 155
7.4 Attribute Access 156
7.5 Scoping Rules 158
Contents ix

7.6 Operator Overloading and Protocols 159


7.7 Inheritance 160
7.8 Avoiding Inheritance via Composition 163
7.9 Avoiding Inheritance via Functions 166
7.10 Dynamic Binding and Duck Typing 167
7.11 The Danger of Inheriting from Built-in
Types 167
7.12 Class Variables and Methods 169
7.13 Static Methods 173
7.14 A Word about Design Patterns 176
7.15 Data Encapsulation and Private
Attributes 176
7.16 Type Hinting 179
7.17 Properties 180
7.18 Types, Interfaces, and Abstract Base
Classes 183
7.19 Multiple Inheritance, Interfaces, and
Mixins 187
7.20 Type-Based Dispatch 193
7.21 Class Decorators 194
7.22 Supervised Inheritance 197
7.23 The Object Life Cycle and Memory
Management 199
7.24 Weak References 204
7.25 Internal Object Representation and
Attribute Binding 206
7.26 Proxies, Wrappers, and Delegation 208
7.27 Reducing Memory Use with
__slots__ 210
7.28 Descriptors 211
7.29 Class Definition Process 215
7.30 Dynamic Class Creation 216
7.31 Metaclasses 217
7.32 Built-in Objects for Instances and
Classes 222
7.33 Final Words: Keep It Simple 223

8 Modules and Packages 225


8.1 Modules and the import Statement 225
x Contents

8.2 Module Caching 227


8.3 Importing Selected Names from a
Module 228
8.4 Circular Imports 230
8.5 Module Reloading and
Unloading 232
8.6 Module Compilation 233
8.7 The Module Search Path 234
8.8 Execution as the Main Program 234
8.9 Packages 235
8.10 Imports Within a Package 237
8.11 Running a Package Submodule as a
Script 238
8.12 Controlling the Package
Namespace 239
8.13 Controlling Package Exports 240
8.14 Package Data 241
8.15 Module Objects 242
8.16 Deploying Python Packages 243
8.17 The Penultimate Word: Start with a
Package 244
8.18 The Final Word: Keep It Simple 245

9 Input and Output 247


9.1 Data Representation 247
9.2 Text Encoding and Decoding 248
9.3 Text and Byte Formatting 250
9.4 Reading Command-Line
Options 254
9.5 Environment Variables 256
9.6 Files and File Objects 256
9.6.1 Filenames 257
9.6.2 File Modes 258
9.6.3 I/O Buffering 258
9.6.4 Text Mode Encoding 259
9.6.5 Text-Mode Line
Handling 260
9.7 I/O Abstraction Layers 260
9.7.1 File Methods 261
Contents xi

9.8 Standard Input, Output, and Error 263


9.9 Directories 264
9.10 The print() function 265
9.11 Generating Output 265
9.12 Consuming Input 266
9.13 Object Serialization 268
9.14 Blocking Operations and
Concurrency 269
9.14.1 Nonblocking I/O 270
9.14.2 I/O Polling 271
9.14.3 Threads 271
9.14.4 Concurrent Execution with
asyncio 272
9.15 Standard Library Modules 273
9.15.1 asyncio Module 273
9.15.2 binascii Module 274
9.15.3 cgi Module 275
9.15.4 configparser Module 276
9.15.5 csv Module 276
9.15.6 errno Module 277
9.15.7 fcntl Module 278
9.15.8 hashlib Module 278
9.15.9 http Package 279
9.15.10 io Module 279
9.15.11 json Module 280
9.15.12 logging Module 280
9.15.13 os Module 281
9.15.14 os.path Module 281
9.15.15 pathlib Module 282
9.15.16 re Module 283
9.15.17 shutil Module 284
9.15.18 select Module 284
9.15.19 smtplib Module 285
9.15.20 socket Module 286
9.15.21 struct Module 288
9.15.22 subprocess Module 288
9.15.23 tempfile Module 289
9.15.24 textwrap Module 290
xii Contents

9.15.25 threading Module 291


9.15.26 time Module 293
9.15.27 urllib Package 293
9.15.28 unicodedata
Module 294
9.15.29 xml Package 295
9.16 Final Words 296

10 Built-in Functions and Standard


Library 297
10.1 Built-in Functions 297
10.2 Built-in Exceptions 314
10.2.1 Exception Base
Classes 314
10.2.2 Exception Attributes 314
10.2.3 Predefined Exception
Classes 315
10.3 Standard Library 318
10.3.1 collections
Module 318
10.3.2 datetime Module 318
10.3.3 itertools Module 318
10.3.4 inspect Module 318
10.3.5 math Module 318
10.3.6 os Module 319
10.3.7 random Module 319
10.3.8 re Module 319
10.3.9 shutil Module 319
10.3.10 statistics
Module 319
10.3.11 sys Module 319
10.3.12 time Module 319
10.3.13 turtle Module 319
10.3.14 unittest Module 319
10.4 Final Words: Use the Built-Ins 320

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.

About the Author


David Beazley is the author of the Python Essential Reference, Fourth Edition
(Addison-Wesley, 2010) and Python Cookbook, Third Edition (O’Reilly, 2013). He
currently teaches advanced computer science courses through his company Dabeaz LLC
( www.dabeaz.com ). He’s been using, writing, speaking, and teaching about Python
since 1996.
1
Python Basics

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.

1.1 Running Python


Python programs are executed by an interpreter. There are many different environments
in which the Python interpreter might run —an IDE, a browser, or a terminal window.
However, underneath all that, the core of the interpreter is a text-based application that
can be started by typing python in a command shell such as bash. Since Python 2 and
Python 3 might both be installed on the same machine, you might need to type python2
or python3 to pick a version. This book assumes Python 3.8 or newer.
When the interpreter starts, a prompt appears where you can type programs into a
so-called “read-evaluation-print loop” (or REPL). For example, in the following output,
the interpreter displays its copyright message and presents the user with the >>> prompt, at
which the user types a familiar “Hello World” program:

Python 3.8.0 (default, Feb 3 2019, 05:53:21)


[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello World')
Hello World
>>>
2 Chapter 1 Python Basics

Certain environments may display a different prompt. The following output is from
ipython (an alternate shell for Python):

Python 3.8.0 (default, Feb 4, 2019, 07:39:16)


Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: print('Hello World')


Hello World

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.

1.2 Python Programs


If you want to create a program that you can run repeatedly, put statements in a text file.
For example:
# hello.py
print('Hello World')

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.

1.3 Primitives, Variables, and Expressions


Python provides a collection of primitive types such as integers, floats, and strings:
42 # int
4.2 # float
'forty-two' # str
True # bool

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 following program uses variables and expressions to perform a compound-interest


calculation:
# interest.py

principal = 1000 # Initial amount


rate = 0.05 # Interest rate
numyears = 5 # Number of years
year = 1
while year <= numyears:
principal = principal * (1 + rate)
print(year, principal)
year += 1

When executed, it produces the following output:


1 1050.0
2 1102.5
3 1157.625
4 1215.5062500000001
5 1276.2815625000003

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

1.4 Arithmetic Operators


Python has a standard set of mathematical operators, shown in Table 1.1. These operators
have the same meaning they do in most other programming languages.

Table 1.1 Arithmetic Operators

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.

Table 1.2 Common Mathematic Functions


Function Description

abs(x) Absolute value


divmod(x,y) Returns (x // y, x % y)
pow(x,y [,modulo]) Returns (x ** y) % modulo
round(x,[n]) Rounds to the nearest multiple of 10 to the nth power.

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

Table 1.3 Bit Manipulation Operators

Operation Description

x << y Left shift


x >> y Right shift
x & y Bitwise and
x | y Bitwise or
x ^ y Bitwise xor (exclusive or)
~x Bitwise negation

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.

Table 1.4 Comparison Operators

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

The result of a comparison is a Boolean value True or False.


The and, or, and not operators (not to be confused with the bit-manipulation
operators above) can form more complex Boolean expressions. The behavior of these
operators is as shown in Table 1.5.
A value is considered false if it is literally False, None, numerically zero, or empty.
Otherwise, it’s considered true.
1.5 Conditionals and Control Flow 7

Table 1.5 Logical Operators

Operator Description

x or y If x is false, return y; otherwise, return x.


x and y If x is false, return x; otherwise, return y.
not x If x is false, return True; otherwise, return False.

It is common to write an expression that updates a value. For example:


x = x + 1
y = y * n

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.

1.5 Conditionals and Control Flow


The while, if and else statements are used for looping and conditional code execution.
Here’s an example:
if a < b:
print('Computer says Yes')
else:
print('Computer says No')

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')

To handle multiple-test cases, use the elif statement:


if suffix == '.htm':
content = 'text/html'
elif suffix == '.jpg':
content = 'image/jpeg'
8 Chapter 1 Python Basics

elif suffix == '.png':


content = 'image/png'
else:
raise RuntimeError(f'Unknown content type {suffix!r}')

If you are assigning a value in combination with a test, use a conditional expression:
maxval = a if a > b else b

This is the same as the longer:


if a > b:
maxval = a
else:
maxval = 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)

The parentheses used to surround an assignment expression are always required.


The break statement can be used to abort a loop early. It only applies to the innermost
loop. For example:
x = 0
while x < 10:
if x == 5:
break # Stops the loop. Moves to Done below
print(x)
x += 1

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

1.6 Text Strings


To define a string literal, enclose it in single, double, or triple quotes as follows:

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

<h1> Hello World </h1>


Click <a href="http://www.python.org">here</a>.
''')

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'
)

If the opening quotation mark of a string is prefaced by an f, escaped expressions


within a string are evaluated. For example, in earlier examples, the following statement was
used to output values of a calculation:
print(f'{year:>3d} {principal:0.2f}')

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

More information about string formatting is found in Chapter 9.


Strings are stored as sequences of Unicode characters indexed by integers, starting at
zero. Negative indices index from the end of the string. The length of a string s is
computed using len(s). To extract a single character, use the indexing operator s[i]
where i is the index.
a = 'Hello World'
print(len(a)) # 11
b = a[4] # b = 'o'
c = a[-1] # c = 'd'

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.

Table 1.6 Common String Methods

Method Description

s.endswith(prefix [,start [,end]]) Checks whether a string ends with prefix.


s.find(sub [, start [,end]]) Finds the first occurrence of the specified
substring sub or -1 if not found.
s.lower() Converts to lowercase.
s.replace(old, new [,maxreplace]) Replaces a substring.
s.split([sep [,maxsplit]]) Splits a string using sep as a delimiter.
maxsplit is the maximum number of splits to
perform.
s.startswith(prefix [,start [,end]]) Checks whether a string starts with prefix.
s.strip([chrs]) Removes leading and trailing whitespace or
characters supplied in chrs.
s.upper() Converts a string to uppercase.

Strings are concatenated with the plus (+) operator:


g = a + 'ly' # g = 'Hello Worldly'
1.6 Text Strings 11

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)

To perform mathematical calculations, a string first has to be converted into a numeric


value using a function such as int() or float(). For example:
z = int(x) + int(y) # z = 79 (Integer Addition)

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

1.7 File Input and Output


The following program opens a file and reads its contents line by line as text strings:
with open('data.txt') as file:
for line in file:
print(line, end='') # end='' omits the extra newline

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

principal = principal * (1 + rate)


print(f'{year:>3d} {principal:0.2f}', file=out)
year += 1

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')

To iterate over the items in a list, use a for loop:


14 Chapter 1 Python Basics

for name in names:


print(name)

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']

Use the plus (+) operator to concatenate lists:


a = ['x','y'] + ['z','z','y'] # Result is ['x','y','z','z','y']

An empty list is created in one of two ways:


names = [] # An empty list
names = list() # An empty list

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(','))

# rows is a list of this form


# [
# ['SYM', '123', '456.78']
# ...
# ]

total = sum([ int(row[1]) * float(row[2]) for row in rows ])


print(f'Total cost: {total:0.2f}')

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:
16 Chapter 1 Python Basics

holding = ('GOOG', 100, 490.10)


address = ('www.python.org', 80)

For completeness, 0- and 1-element tuples can be defined, but have special syntax:
a = () # 0-tuple (empty tuple)
b = (item,) # 1-tuple (note the trailing comma)

The values in a tuple can be extracted by numerical index just like a list. However, it is
more common to unpack tuples into a set of variables, like this:
name, shares, price = holding
host, port = address

Although tuples support most of the same operations as lists (such as indexing, slicing,
and concatenation), the elements of a tuple cannot be changed after creation — that is, you
cannot replace, delete, or append new elements to an existing tuple. A tuple is best viewed
as a single immutable object that consists of several parts, not as a collection of distinct
objects like a list.
Tuples and lists are often used together to represent data. For example, this program
shows how you might read a file containing columns of data separated by commas:
# File containing lines of the form ``name,shares,price"
filename = 'portfolio.csv'

portfolio = []
with open(filename) as file:
for line in file:
row = line.split(',')
name = row[0]
shares = int(row[1])
price = float(row[2])
holding = (name, shares, price)
portfolio.append(holding)

The resulting portfolio list created by this program looks like a two-dimensional array
of rows and columns. Each row is represented by a tuple and can be accessed as follows:
>>> portfolio[0]
('AA', 100, 32.2)
>>> portfolio[1]
('IBM', 50, 91.1)
>>>

Individual items of data can be accessed like this:


>>> portfolio[1][1]
50
1.10 Sets 17

>>> portfolio[1][2]
91.1
>>>

Here’s how to loop over all of the records and unpack fields into a set of variables:
total = 0.0
for name, shares, price in portfolio:
total += shares * price

Alternatively, you could use a list comprehension:


total = sum([shares * price for _, shares, price in portfolio])

When iterating over tuples, the variable _ can be used to indicate a discarded value. In
the above calculation, it means we’re ignoring the first item (the name).

1.10 Sets
A set is an unordered collection of unique objects. Sets are used to find distinct values or to
manage problems related to membership. To create a set, enclose a collection of values in
curly braces or give an existing collection of items to set(). For example:
names1 = { 'IBM', 'MSFT', 'AA' }
names2 = set(['IBM', 'MSFT', 'HPE', 'IBM', 'CAT'])

The elements of a set are typically restricted to immutable objects. For example, you can
make a set of numbers, strings, or tuples. However, you can’t make a set containing lists.
Most common objects will probably work with a set, however— when in doubt, try it.
Unlike lists and tuples, sets are unordered and cannot be indexed by numbers.
Moreover, the elements of a set are never duplicated. For example, if you inspect the value
of names2 from the preceding code, you get the following:
>>> names2
{'CAT', 'IBM', 'MSFT', 'HPE'}
>>>

Notice that 'IBM' only appears once. Also, the order of items can’t be predicted; the
output may vary from what’s shown. The order might even change between interpreter
runs on the same computer.
If working with existing data, you can also create a set using a set comprehension. For
example, this statement turns all of the stock names from the data in the previous section
into a set:
names = { s[0] for s in portfolio }
18 Chapter 1 Python Basics

To create an empty set, use set() with no arguments:


r = set() # Initially empty set

Sets support a standard collection of operations including union, intersection,


difference, and symmetric difference. Here’s an example:
a = t | s # Union {'MSFT', 'CAT', 'HPE', 'AA', 'IBM'}
b = t & s # Intersection {'IBM', 'MSFT'}
c = t - s # Difference { 'CAT', 'HPE' }
d = s - t # Difference { 'AA' }
e = t ^ s # Symmetric difference { 'CAT', 'HPE', 'AA' }

The difference operation s - t gives items in s that aren’t in t. The symmetric


difference s ^ t gives items that are in either s or t but not in both.
New items can be added to a set using add() or update():
t.add('DIS') # Add a single item
s.update({'JJ', 'GE', 'ACME'}) # Adds multiple items to s

An item can be removed using remove() or discard():


t.remove('IBM') # Remove 'IBM' or raise KeyError if absent.
s.discard('SCOX') # Remove 'SCOX' if it exists.

The difference between remove() and discard() is that discard() doesn’t raise an
exception if the item isn’t present.

1.11 Dictionaries
A dictionary is a mapping between keys and values. You create a dictionary by enclosing
the key-value pairs, each separated by a colon, in curly braces ({ }), like this:
s = {
'name' : 'GOOG',
'shares' : 100,
'price' : 490.10
}

To access members of a dictionary, use the indexing operator as follows:


name = s['name']
cost = s['shares'] * s['price']

Inserting or modifying objects works like this:


s['shares'] = 75
s['date'] = '2007-06-07'
1.11 Dictionaries 19

A dictionary is a useful way to define an object that consists of named fields. However,
dictionaries are also commonly used as a mapping for performing fast lookups on
unordered data. For example, here’s a dictionary of stock prices:

prices = {
'GOOG' : 490.1,
'AAPL' : 123.5,
'IBM' : 91.5,
'MSFT' : 52.13
}

Given such a dictionary, you can look up a price:


p = prices['IBM']

Dictionary membership is tested with the in operator:


if 'IBM' in prices:
p = prices['IBM']
else:
p = 0.0

This particular sequence of steps can also be performed more compactly using the
get() method:
p = prices.get('IBM', 0.0) # prices['IBM'] if it exists, else 0.0

Use the del statement to remove an element of a dictionary:


del prices['GOOG']

Although strings are the most common type of key, you can use many other Python
objects, including numbers and tuples. For example, tuples are often used to construct
composite or multipart keys:
prices = { }
prices[('IBM', '2015-02-03')] = 91.23
prices['IBM', '2015-02-04'] = 91.42 # Parens omitted

Any kind of object can be placed into a dictionary, including other dictionaries.
However, mutable data structures such as lists, sets, and dictionaries cannot be used as keys.
Dictionaries are often used as building blocks for various algorithms and data-handling
problems. One such problem is tabulation. For example, here’s how you could count the
total number of shares for each stock name in earlier data:
portfolio = [
('ACME', 50, 92.34),
('IBM', 75, 102.25),
('PHP', 40, 74.50),
20 Chapter 1 Python Basics

('IBM', 50, 124.75)


]

total_shares = { s[0]: 0 for s in portfolio }


for name, shares, _ in portfolio:
total_shares[name] += shares

# total_shares = {'IBM': 125, 'ACME': 50, 'PHP': 40}

In this example, { s[0]: 0 for s in portfolio } is an example of a dictionary


comprehension. It creates a dictionary of key-value pairs from another collection of data.
In this case, it’s making an initial dictionary mapping stock names to 0. The for loop that
follows iterates over the dictionary and adds up all of the held shares for each stock symbol.
Many common data processing tasks such as this one have already been implemented by
library modules. For example, the collections module has a Counter object that can be
used for this task:
from collections import Counter

total_shares = Counter()
for name, shares, _ in portfolio:
total_shares[name] += shares

# total_shares = Counter({'IBM': 125, 'ACME': 50, 'PHP': 40})

An empty dictionary is created in one of two ways:


prices = {} # An empty dict
prices = dict() # An empty dict

It is more idiomatic to use {} for an empty dictionary — although caution is required


since it might look like you are trying to create an empty set (use set() instead). dict() is
commonly used to create dictionaries from key-value values. For example:
pairs = [('IBM', 125), ('ACME', 50), ('PHP', 40)]
d = dict(pairs)

To obtain a list of dictionary keys, convert a dictionary to a list:


syms = list(prices) # syms = ['AAPL', 'MSFT', 'IBM', 'GOOG']

Alternatively, you can obtain the keys using dict.keys():


syms = prices.keys()

The difference between these two methods is that keys() returns a special “keys view”
that is attached to the dictionary and actively reflects changes made to the dictionary. For
example:
1.12 Iteration and Looping 21

>>> d = { 'x': 2, 'y':3 }


>>> k = d.keys()
>>> k
dict_keys(['x', 'y'])
>>> d['z'] = 4
>>> k
dict_keys(['x', 'y', 'z'])
>>>

The keys always appear in the same order as the items were initially inserted into the
dictionary. The list conversion above will preserve this order. This can be useful when dicts
are used to represent key-value data read from files and other data sources. The dictionary
will preserve the input order. This might help readability and debugging. It’s also nice if
you want to write the data back to a file. Prior to Python 3.6, however, this ordering was
not guaranteed, so you cannot rely upon it if compatibility with older versions of Python is
required. Order is also not guaranteed if multiple deletions and insertions have taken place.
To obtain the values stored in a dictionary, use the dict.values() method. To obtain
key-value pairs, use dict.items(). For example, here’s how to iterate over the entire
contents of a dictionary as key-value pairs:
for sym, price in prices.items():
print(f'{sym} = {price}')

1.12 Iteration and Looping


The most widely used looping construct is the for statement that iterates over a collection
of items. One common form of iteration is to loop over all the members of a
sequence —such as a string, list, or tuple. Here’s an example:
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(f'2 to the {n} power is {2**n}')

In this example, the variable n will be assigned successive items from the list [1, 2, 3,
4, ..., 9] on each iteration. Since looping over ranges of integers is quite common,
there is a shortcut:
for n in range(1, 10):
print(f'2 to the {n} power is {2**n}')

The range(i, j [,step]) function creates an object that represents a range of integers
with values from i up to, but not including, j. If the starting value is omitted, it’s taken to
be zero. An optional stride can also be given as a third argument. Here are some examples:
a = range(5) # a = 0, 1, 2, 3, 4
b = range(1, 8) # b = 1, 2, 3, 4, 5, 6, 7
c = range(0, 14, 3) # c = 0, 3, 6, 9, 12
d = range(8, 1, -1) # d = 8, 7, 6, 5, 4, 3, 2
22 Chapter 1 Python Basics

The object created by range() computes the values it represents on demand when
lookups are requested. Thus, it’s efficient to use even with a large range of numbers.
The for statement is not limited to sequences of integers. It can be used to iterate over
many kinds of objects including strings, lists, dictionaries, and files. Here’s an example:
message = 'Hello World'
# Print out the individual characters in message
for c in message:
print(c)

names = ['Dave', 'Mark', 'Ann', 'Phil']


# Print out the members of a list
for name in names:
print(name)

prices = { 'GOOG' : 490.10, 'IBM' : 91.50, 'AAPL' : 123.15 }


# Print out all of the members of a dictionary
for key in prices:
print(key, '=', prices[key])

# Print all of the lines in a file


with open('foo.txt') as file:
for line in file:
print(line, end='')

The for loop is one of Python’s most powerful language features because you can create
custom iterator objects and generator functions that supply it with sequences of values.
More details about iterators and generators can be found later in Chapter 6.

1.13 Functions
Use the def statement to define a function:
def remainder(a, b):
q = a // b # // is truncating division.
r = a - q * b
return r

To invoke a function, use its name followed by its arguments in parentheses, for
example result = remainder(37, 15).
It is common practice for a function to include a documentation string as the first
statement. This string feeds the help() command and may be used by IDEs and other
development tools to assist the programmer. For example:
def remainder(a, b):
'''
1.13 Functions 23

Computes the remainder of dividing a by b


'''
q = a // b
r = a - q * b
return r

If the inputs and outputs of a function aren’t clear from their names, they might be
annotated with types:
def remainder(a: int, b: int) -> int:
'''
Computes the remainder of dividing a by b
'''
q = a // b
r = a - q * b
return r

Such annotations are merely informational and are not actually enforced at runtime.
Someone could still call the above function with non-integer values, such as result =
remainder(37.5, 3.2).
Use a tuple to return multiple values from a function:
def divide(a, b):
q = a // b # If a and b are integers, q is integer
r = a - q * b
return (q, r)

When multiple values are returned in a tuple, they can be unpacked into separate
variables like this:
quotient, remainder = divide(1456, 33)

To assign a default value to a function parameter, use assignment:


def connect(hostname, port, timeout=300):
# Function body
...

When default values are given in a function definition, they can be omitted from
subsequent function calls. An omitted argument will take on the supplied default value.
Here’s an example:
connect('www.python.org', 80)
connect('www.python.org', 80, 500)

Default arguments are often used for optional features. If there are many such
arguments, readability can suffer. It’s therefore recommended to specify such arguments
using keyword arguments. For example:
24 Chapter 1 Python Basics

connect('www.python.org', 80, timeout=500)

If you know the names of the arguments, all of them can be named when calling a
function. When named, the order in which they are listed doesn’t matter. For example,
this is fine:
connect(port=80, hostname='www.python.org')

When variables are created or assigned inside a function, their scope is local. That is,
the variable is only defined inside the body of the function and is destroyed when the
function returns. Functions can also access variables defined outside of a function as long as
they are defined in the same file. For example:
debug = True # Global variable

def read_data(filename):
if debug:
print('Reading', filename)
...

Scoping rules are described in more detail in Chapter 5.

1.14 Exceptions
If an error occurs in your program, an exception is raised and a traceback message appears:
Traceback (most recent call last):
File "readport.py", line 9, in <module>
shares = int(row[1])
ValueError: invalid literal for int() with base 10: 'N/A'

The traceback message indicates the type of error that occurred, along with its location.
Normally, errors cause a program to terminate. However, you can catch and handle
exceptions using try and except statements, like this:
portfolio = []
with open('portfolio.csv') as file:
for line in file:
row = line.split(',')
try:
name = row[0]
shares = int(row[1])
price = float(row[2])
holding = (name, shares, price)
portfolio.append(holding)
except ValueError as err:
1.14 Exceptions 25

print('Bad row:', row)


print('Reason:', err)

In this code, if a ValueError occurs, details concerning the cause of the error are placed
in err and control passes to the code in the except block. If some other kind of exception
is raised, the program crashes as usual. If no errors occur, the code in the except block is
ignored. When an exception is handled, program execution resumes with the statement
that immediately follows the last except block. The program does not return to the
location where the exception occurred.
The raise statement is used to signal an exception. You need to give the name of an
exception. For instance, here’s how to raise RuntimeError, a built-in exception:
raise RuntimeError('Computer says no')

Proper management of system resources such as locks, files, and network connections is
often tricky when combined with exception handling. Sometimes there are actions that
must be performed no matter what happens. For this, use try-finally. Here is an
example involving a lock that must be released to avoid deadlock:
import threading
lock = threading.Lock()
...
lock.acquire()
# If a lock has been acquired, it MUST be released
try:
...
statements
...
finally:
lock.release() # Always runs

To simplify such programming, most objects that involve resource management also
support the with statement. Here is a modified version of the above code:

with lock:
...
statements
...

In this example, the lock object is automatically acquired when the with statement
executes. When execution leaves the context of the with block, the lock is automatically
released. This is done regardless of what happens inside the with block. For example, if an
exception occurs, the lock is released when control leaves the context of the block.
The with statement is normally only compatible with objects related to system
resources or the execution environment— such as files, connections, and locks. However,
user-defined objects can have their own custom processing, as described further in
Chapter 3.
26 Chapter 1 Python Basics

1.15 Program Termination


A program terminates when no more statements exist to execute in the input program or
when an uncaught SystemExit exception is raised. If you want to force a program to quit,
here’s how to do it:
raise SystemExit() # Exit with no error message
raise SystemExit("Something is wrong") # Exit with error

On exit, the interpreter makes a best effort to garbage-collect all active objects.
However, if you need to perform a specific cleanup action (remove files, close a
connection), you can register it with the atexit module as follows:
import atexit

# Example
connection = open_connection("deaddot.com")

def cleanup():
print "Going away..."
close_connection(connection)

atexit.register(cleanup)

1.16 Objects and Classes


All values used in a program are objects. An object consists of internal data and methods
that perform various kinds of operations involving that data. You have already used objects
and methods when working with the built-in types such as strings and lists. For example:
items = [37, 42] # Create a list object
items.append(73) # Call the append() method

The dir() function lists the methods available on an object. It is a useful tool for
interactive experimentation when no fancy IDE is available. For example:
>>> items = [37, 42]
>>> dir(items)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
...
'append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
>>>

When inspecting objects, you will see familiar methods such as append() and insert()
listed. However, you will also see special methods whose names begin and end with a
1.16 Objects and Classes 27

double underscore. These methods implement various operators. For example, the
__add__() method is used to implement the + operator. These methods are explained in
more detail in later chapters.
>>> items.__add__([73, 101])
[37, 42, 73, 101]
>>>

The class statement is used to define new types of objects and for object-oriented
programming. For example, the following class defines a stack with push() and pop()
operations:
class Stack:
def __init__(self): # Initialize the stack
self._items = [ ]

def push(self, item):


self._items.append(item)

def pop(self):
return self._items.pop()

def __repr__(self):
return f'<{type(self).__name__} at 0x{id(self):x}, size={len(self)}>'

def __len__(self):
return len(self._items)

Inside the class definition, methods are defined using the def statement. The first
argument in each method always refers to the object itself. By convention, self is the
name used for this argument. All operations involving the attributes of an object must
explicitly refer to the self variable.
Methods with leading and trailing double underscores are special methods. For
example, __init__ is used to initialize an object. In this case, __init__ creates an internal
list for storing the stack data.
To use a class, write code such as this:
s = Stack() # Create a stack
s.push('Dave') # Push some things onto it
s.push(42)
s.push([3, 4, 5])
x = s.pop() # x gets [3,4,5]
y = s.pop() # y gets 42

Within the class, you will notice that the methods use an internal _items variable.
Python does not have any mechanism for hiding or protecting data. However, there is a
programming convention wherein names preceded by a single underscore are taken to be
28 Chapter 1 Python Basics

“private.” In this example, _items should be treated (by you) as internal implementation
and not used outside the Stack class itself. Be aware that there is no actual enforcement of
this convention —if you want to access _items, you can do so at any time. You’ll just have
to answer to your coworkers when they review your code.
The __repr__() and __len__() methods are there to make the object play nicely with
the rest of the environment. Here, __len__() makes a Stack work with the built-in len()
function and __repr__() changes the way that a Stack is displayed and printed. It’s a good
idea to always define __repr__() as it can simplify debugging.
>>> s = Stack()
>>> s.push('Dave')
>>> s.push(42)
>>> len(s)
2
>>> s
<Stack at 0x10108c1d0, size=2>
>>>

A major feature of objects is that you can add to or redefine the capabilities of existing
classes via inheritance.
Suppose you wanted to add a method to swap the top two items on the stack. You
might write a class like this:
class MyStack(Stack):
def swap(self):
a = self.pop()
b = self.pop()
self.push(a)
self.push(b)

MyStack is identical to Stack except that it has a new method, swap().


>>> s = MyStack()
>>> s.push('Dave')
>>> s.push(42)
>>> s.swap()
>>> s.pop()
'Dave'
>>> s.pop()
42
>>>

Inheritance can also be used to change the behavior of an existing method. Suppose
you want to restrict the stack to only hold numeric data. Write a class like this:
class NumericStack(Stack):
def push(self, item):
1.16 Objects and Classes 29

if not isinstance(item, (int, float)):


raise TypeError('Expected an int or float')
super().push(item)

In this example, the push() method has been redefined to add extra checking. The
super() operation is a way to invoke the prior definition of push(). Here’s how this class
would work:
>>> s = NumericStack()
>>> s.push(42)
>>> s.push('Dave')
Traceback (most recent call last):
...
TypeError: Expected an int or float
>>>

Often, inheritance is not the best solution. Suppose you wanted to define a simple
stack-based 4-function calculator that worked like this:
>>> # Calculate 2 + 3 * 4
>>> calc = Calculator()
>>> calc.push(2)
>>> calc.push(3)
>>> calc.push(4)
>>> calc.mul()
>>> calc.add()
>>> calc.pop()
14
>>>

You might look at this code, see the use of push() and pop(), and think that
Calculator could be defined by inheriting from Stack. Although that would work, it is
probably better to define Calculator as a completely separate class:
class Calculator:
def __init__(self):
self._stack = Stack()

def push(self, item):


self._stack.push(item)

def pop(self):
return self._stack.pop()

def add(self):
self.push(self.pop() + self.pop())
30 Chapter 1 Python Basics

def mul(self):
self.push(self.pop() * self.pop())

def sub(self):
right = self.pop()
self.push(self.pop() - right)

def div(self):
right = self.pop()
self.push(self.pop() / right)

In this implementation, a Calculator contains a Stack as an internal implementation


detail. This is an example of composition. The push() and pop() methods delegate to the
internal Stack. The main reason for taking this approach is that you don’t really think of
the Calculator as a Stack. It’s a separate concept — a different kind of object. By analogy,
your phone contains a central processing unit (CPU) but you don’t usually think of your
phone as a type of CPU.

1.17 Modules
As your programs grow in size, you will want to break them into multiple files for easier
maintenance. To do this, use the import statement. To create a module, put the relevant
statements and definitions into a file with a .py suffix and the same name as the module.
Here’s an example:
# readport.py
#
# Reads a file of 'NAME,SHARES,PRICE' data

def read_portfolio(filename):
portfolio = []
with open(filename) as file:
for line in file:
row = line.split(',')
try:
name = row[0]
shares = int(row[1])
price = float(row[2])
holding = (name, shares, price)
portfolio.append(holding)
except ValueError as err:
print('Bad row:', row)
print('Reason:', err)
return portfolio
Discovering Diverse Content Through
Random Scribd Documents
attack upon Christianity itself. They have tauntingly urged the narrow
extent of our religion as an argument against its Divinity. That
argument admits, even now, of solid refutation. But in due season the
fact itself shall be altered, and no shadow of plausibility shall be left for
the reproach (chap. liv. 1–5).
Concluding observations.
1. The text should teach you your personal obligations and privileges in
reference to the Gospel. The feast is spread out before you; to you are
the blessings of it freely offered (chap. lv. 1–3).
2. The text teaches you the ground of missionary exertions. To partake
of the feast ourselves is our first duty: but, while we “eat the fat and
drink the sweet,” shall we not “send portions unto them for whom
nothing is prepared?” Can any duty be more obviously founded in
reason and justice, humanity and piety, than that of sending the bread
of life to our perishing fellow-creatures? The most hateful and
inexcusable of all monopolies is the monopoly of Christian truths and
consolations.
3. There are great encouragements to such labour. (1.) The certainty of
Divine approbation. (2.) The certainty of consequent success (H. E. I.
1166–1168). But remember, if you would share in the triumphs of the
Gospel, you must share in the labour and expense of their
achievement.—Jabez Bunting, D.D.: Sermons, vol. i. pp. 453–483.

Peaceful Keeping.

xxvi. 3, 4. Thou wilt keep him in perfect peace, &c.


The delightfulness and value of peace to the nation, the Church, the
family, the individual (P. D. 2664). Consider—
I. The promise. 1. It is universal in its range. It is made to any and
every man who will trust in God. 2. It is sure. Men fail for various
reasons to keep their promises, but every Divine promise is certain to
be fulfilled (H. E. I. 4052, 4053). 3. The peace which is pledged and
secured to all who will fulfil the condition of the text is perfect—
so perfect that it can only be described by a repetition of the word,
“peace, peace.” God never gives in driblets. His gifts are like Himself,
perfect for their fulness, for their suitability, for their enduring
qualities. God can keep His people in perfect peace when the devil
accuses, when the world allures or threatens, when sickness tries, when
adversity oppresses, even when the heart is sore tired, and when grim
death would affright (H. E. I. 1253, 1893, 1894, 1911–1926; P. D. 2669,
2673).
II. The character described. “Whose mind is stayed on Thee, because he
trusted in Thee.” Trust unites. The mind will not be stayed upon God
unless there be perfect confidence in His wisdom, power, and love.
Trust and love go together. Love begets confidence, and confidence
strengthens love. The whole nature must be stayed on God, and on
God only. There must be no division in the heart’s affections: we
cannot serve God and Mammon and be kept in perfect peace. There
must be trust before there can be peace; God Himself cannot give
perfect peace to the untrustful.
III. The exhortation. “Trust ye in the Lord for ever.” We trust in the Lord
when, encouraged by His promises, we hold fast to Him. It is nothing
deeper, nothing more difficult than that. Its very simplicity is its
difficulty. As the limpet binds itself to the rock, and is not disturbed by
the dashing billows, so let the soul by an ardent affection bind itself to
the Rock of Ages. The word “ever” gives a wonderful expansiveness to
our text. It points at once to God’s eternity and man’s immortality. He
is a being capable of being trusted for ever, and for ever we shall be
capable of trusting Him. Our trust is to be unlimited and
unintermitted; it is to be exercised at all times, under all
circumstances, through all ages.
IV. The stable foundation of the believer’s confidence. “For in the Lord
Jehovah is everlasting strength.” The peace must be perfect that rests
upon, and rises out of, such a solid foundation. The mountains are
“everlasting” only in figure, but the foundation on which we rest is
everlasting in fact (Ps. xci. 1, 2).—W. Burrows, B.A.

The world needs the message contained in our text. Most faces that we
see are careworn. They are so because behind them there are anxious
hearts distressed by fears of various kinds—by fears concerning the
body, by fears concerning the soul. The vast majority of men are
destitute of true peace; for while in the world there are many ways—of
pleasure, of sin, of disappointment, of misery, of death—there is no
way of peace. The multitudes who throng past us are miserable
because the way of peace they have not known.
I. Look at the person who is kept in peace. He is a person whose mind
is stayed on God. A man’s self, sin, pleasure, false religion, vain hopes,
are every one of them troubled waves in an ocean of disquietude, and
no soul can stay itself on them, though many souls have sought to do
so. Who, lying down in the very midst of the sea, can find there repose?
As he lieth down upon the waves, they yield beneath him—the billows
roll over him; he is sinking in the mighty deep. So with the sinner lying
down in the midst of the sea and of the storm of this world apart from
God. But he who lieth down upon God is as a man upon a rock, or as
one in a mighty fortress; he is at peace—secure in fact and in feeling.
But it is only as God is revealed to us in Christ that we may rest upon
Him. Apart from Christ, He is to sinners “a consuming fire.” Only
through Christ may we find the blessedness we so much need, but
through Christ we may find it.
II. Look at the power which keeps the believer in peace. It is not the
power of his own faith (H. E. I. 1970, 1975). It is not the power of his
own effort, struggling to obtain confidence. It is the power of God:
“Thou wilt keep him,” &c. The sinner obtains peace by yielding himself
to God (Rom. vi. 13). The believer has peace while he leaves himself in
God’s hands, quietly submissive, cheerfully willing that God should
lead him and do with him whatever is pleasing in His sight (P. D. 2966–
2968, 2970–2972). Then all God’s attributes—His omniscience, His
omnipotence, His faithfulness, His tender mercy—minister to his
peace (P. D. 3379).
III. Look at the peace in which such a person is kept. It is “perfect
peace.” Peace in spite of all that conscience may say, of the temptations
that assail us, of the troubles of life, of the certainty and mystery of
death. With the peace of pardon, all this peace flows into the soul,
increasing more and more. It is the peace of Christ, the same peace
which filled and sustained Him (John xiv. 27). You remember that we
are shown Him with His head on a pillow, His eyes closed, His mind in
unconscious repose, asleep in the midst of the wild storm at night
upon the Lake of Galilee, when the waves beat upon the trembling
vessel, and the wind strove to raise the waves still higher, and engulph
them all. He slept, secure and peaceful, amid the storm. So does the
soul of the believer that stayeth itself upon God. Upon what lay that
peaceful head of Jesus but upon the unseen arm and heart of God. Men
said of Christ mockingly, “He trusted in God.” He did trust in God, as
the most exalted believer, and far more than the most exalted believer;
and in that simplicity of faith He was kept in peace, sleeping amidst
the storm. So is it with the believer. O believer! is it so with you?—
Henry Grattan Guinness: Sermon in The Christian World, 1860.

Here is the secret of life—peace, perfect peace—and the sure way of


attaining it. Consider—
I. The character contemplated. “Whose mind is stayed on Thee.” His
mind is fixed with such intensity that it cannot be diverted from the
object on which it is set. This object is not himself (Prov. xxviii. 26), nor
his riches (Prov. xxiii. 5), nor his fellow-men (Ch. ii. 22; Jer. xvii. 4, 5),
but God, in whom he trusts unhesitatingly, exclusively, universally. He
accepts all that the Scriptures reveal concerning God, and makes these
revelations the foundation of his confidence and his prayers.
II. The promised blessing. “Thou wilt keep him in perfect peace.” See
also Jer. xvii. 7. The idea suggested is that of habitual and continued
blessedness. The elements of peace are begun in the soul, and they are
brought to maturity in the whole course of the future life. The peace
given is like a river (chap. lxvi. 12), both for abundance and
permanence. That is, while, and only while, the mind is stayed upon
God (chap. xlviii. 18). Then he is kept in peace, for God is its finisher as
well as its author; and it is “perfect peace,” because it is peace of all
kinds, in its highest degree, at all times, under all circumstances.
III. The reason for the bestowment of the blessing. “Because he trusteth
in Thee.” Faith honours God (Rom. iv. 21), and therefore those who
exercise it are honoured by Him (1 Sam. ii. 30; H. E. I. 4057, 4058).
IV. The duty enjoined. “Trust ye,” &c. While we are listening to
expositions of this text, this duty seems to be easy; but in actual life our
faith is tried and often fails, because we lose sight of the promises and
perfections of God. Here there come to us disappointments,
difficulties, temptations to distrust. But it is our duty to struggle with
them all; and if we do so, it will be our blessedness to overcome them
all (chap. xl. 27–31). “Trust ye in the Lord; trust ye in the Lord for ever;
for in the Lord Jehovah is everlasting strength.”—James Morgan, D.D.:
The Home Pulpit, pp. 512–516.

There is sometimes a world of meaning in a single word: Country,


home, peace! How it sometimes tells of booming cannon hushed into
silence, of glittering swords sent back into their sheaths, of hundreds
of homes relieved from distressing anxieties and fears, of thousands of
lives respited at least for a time! How it sometimes tells of surging
passions hushed into a calm, of vengeful purposes superseded, of the
fires of enmity quenched, of despair giving place to hope and joy! Peace
has its histories, many and pleasant; its triumphs, various and
substantial; its heralds, Divine, angelic, human. Ministers have
messages of peace to deliver to their congregations, and in our text we
have one of them.
I. The condition expressed in the text. “Whose mind is stayed on Thee.”
It is a mind resting on God as the God of grace reconciling sinners to
Himself through the mediation of Christ, dispensing pardon, sanctity,
salvation—a mind resting, after reconciliation, on His truthfulness,
wisdom, almightiness, holiness—a mind resting on His rule and
government over all the forces of nature and all the events of daily life,
both national and individual.
II. The confidence expressed in the text. “Thou wilt keep,” &c. Thou wilt
do it; not merely delegate and intrust this to any agency whatever.
Thou wilt do it; there is no uncertainty or peradventure about it. “In
perfect peace:” peace of all kinds, and in a superlative degree; peace
flowing from reconciliation; peace in the midst of unexplained
mysteries; peace in the midst of adverse providences; peace amid the
uncertainties of the future.—John Corbin.

The Song to the Vineyard.

xxvii. 2, 3. In that day sing ye unto her, &c.


There are different opinions as to what is meant by “leviathan, that
crooked serpent,” and “the dragon that is in the sea” (ver. 1), whether
the same power is signified by different names, &c. (1.) On a point
concerning which learned and able men cannot see eye to eye, it would
be presumptuous for me to give an opinion. (2.) If we cannot feel
certain as to the literal meaning, the spiritual is plain. (3.) Neither of
the expositions affects the substance of the prophecy. A great
deliverance is spoken of, to be accomplished by the destruction of the
enemies of the Church, and the Lord gives a command to comfort His
people. There is in our text a command and a promise.
I. The command.
1. “Sing ye unto her.” It is taken for granted that the spiritual condition
of the Church is pleasing to God, but that the feeling of His people is in
a low state. Sometimes the Lord directs His servant to reprimand
them: “Show unto my people their transgressions.” A Church may need
comfort while some of its members deserve correction. Possibly the
faulty members are the cause of the discomfort to the Church, and
render it desirable that she should be comforted. It is so in the family.
We comfort the family when a member of it has transgressed. The fact
that one member needs correction causes the others to need
consolation. In some cases, it requires much wisdom to decide whether
an encouragement or a reproof should be given. We have seen the rod
used when a kind word would have been more suitable; and some are
singing songs while it would be more appropriate to sound an alarm.
There is need for rightly dividing the Word of truth. “A word in its
season,” &c.
Possibly the accurate expositor will ask who is commanded to sing. Is it
the prophets, or the priests, or the choir of the Temple? This is a
poetical book, and sometimes it calls on the heavens, the mountains,
and the trees of the field to sing. In this respect I would rather let the
command of the text remain undecided, and say to everybody and
everything, “Sing unto her!”
2. What should be sung to this vineyard? Remind her in this song that
she is “the vineyard of the Lord of hosts.” The Old Testament is full of
references to a vineyard, to vines, and to wine. The reason for this is,
that the Bible is an Eastern book. A vineyard supposes—
Separation. Not the superiority of its soil to that of the surrounding
country makes the vineyard, but its separation. It is not because the
saints are by nature better than others that they are God’s vineyard, but
because they are set apart by Him. The idea of separation as regards
the Church is made conspicuous in every age. The saints, the disciples,
constitute the flock and the vineyard of the Old Testament, the Church
of the New. When I speak of a separated Church, of course I do not
allude to any sect, but to the Church in general. There are hypocrites in
the Churches, but none in the Church. It is in the world, but not of the
world. The soul is in the body, but not of the body “Wherefore, come
out from among them, and be ye separate, saith the Lord” (2 Cor.
vi. 17). Ceremonials cannot plant the vine; there are necessarily
ordinances, but circumcision could not make the Jews a godly people,
and there were thousands of ungodly people partaking every year of
the Passover. A change of heart, a change in the condition of the soul,
constitutes the planting in the vineyard; not a ceremonial separation,
but a change of mind; not the affixing of the stamp of a sect, but the
impartation of the image of God (H. E. I. 1171–1183).
II. The promise.
A large and comprehensive one. It includes—
1. Care. “I the Lord do keep it.” With regard to a vineyard, there is a
special meaning in the word “keep.” The vine requires great care. There
is much work for the knife. From the pruning of the vine by the vine-
dresser, there is much valuable instruction to be gained. We learn that
what appear to be grievous losses may secure great gains (H. E. I. 63,
104, 126). Oh, this pruning how painful it often is! But it is not done
because the Owner of the vineyard delights in it; it proves His love. See
Jochebed taking an ark of bulrushes, putting the child Moses in it, and
then laying it amidst the perils of the Nile: not because she hated him!
No; love was at the bottom of it all, though it appeared otherwise. It
behoves the pulpit still to assure God’s people of His care for them.
2. Provision. “I will water it.” There was necessity for watering the
vineyard constantly. This was done by means of trenches conveying the
water to the roots of the plants. For this purpose rain-water was
carefully stored in cisterns; dew was also of great service. The means of
grace are somewhat like watercourses. We are dry enough and withered
in appearance, but what would we be without the means of grace?
What is the dew? The noiseless influences of the Holy Spirit. We will
compare revivals to showers; they are not with us, like the
watercourses, always. I do not know whether the natural vineyards
must have water without intermission; but the vineyard of the Lord of
hosts requires it “every moment,” and here is His promise to supply the
need.
3. Safety. “Lest any hurt it, I will keep it night and day.” It shall be
protected from the blighting frost, from thieves and spoilers, from “the
boar out of the wood,” from “the little foxes that spoil the vines.” “I the
Lord do keep it.” He will not only give His angels charge concerning it,
though He will do that. “The angel of the Lord encampeth round about
them that fear Him.” That shall be done and more! “For I, saith the
Lord, will be unto her a wall of fire round about her, and will be the
glory in the midst of her.” All things are in the hand of God, and under
His control they shall co-operate for her safety. It is not surprising that
Moses, as he surveyed Israel from the top of Mount Nebo, should say,
“Happy art thou, O Israel! who is like unto thee, O people saved by the
Lord, the shield of thy help? The eternal God is thy refuge, and
underneath are the everlasting arms.” “He that dwelleth in the secret
place of the Most High shall abide under the shadow of the Almighty.”
In dwelling near God there is safety. Israel was always flourishing when
with God. The safety of God’s people means more than being kept
together and saved from destruction: “Lest any hurt it!” How excellent
are the promises of God!—Gweithiau Rhyddieithol, pp. 48–51, by the
late William Ambrose of Portmadoc, translated from the Welsh by the
Rev. T. Johns, of Llanelly.

The Storms of Life.

xxvii. 8. In measure when it shooteth forth, &c.


I. There is a special appropriateness in comparing the trials of
life to storms. 1. Storms are the exceptions and not the normal or
common condition of the atmosphere. “In the world ye shall have
tribulation.” True; but Christ in saying so does not assert that we shall
have tribulation only. “Man is born unto trouble, as the sparks fly
upward.” Yes; but it is not said that there is nothing but trouble.
“Through much tribulation,” &c. Yea, through many storms the
mariner has to go through life; but there is fine weather also. 2. Storms
come from God. See what is said about trouble (Job v. 6), “All my
springs are in Thee,” the sweet and the bitter. 3. Storms come from
different directions: the family, the Church, business, &c. 4. Storms are
unpleasant to bear. The anxiety of the sailor’s wife. The traveller on the
moor. 5. Storms leave their traces behind. The ravages of the sea. The
effects of gales on edifices. So in life. The bereaved family. The
capitalist reduced to want, &c. 6. But storms are beneficial (Heb. xii. 10,
11).
II. The storms of life are regulated and controlled by God. It is of
Him that our text speaks. Who “debates in measure?” Who “stayeth
His rough wind in the day of His east wind?” He who is almighty, all-
wise, and good. His greatness, as shown in the firmament, hints that
He is too great to observe human beings. But notice our Saviour’s
teaching: while instructing us concerning His Father, He speaks not of
His omnipotence, &c., but of His observation of small things (Matt.
x. 29, 30). Put a green leaf or a drop of water under a microscope, and
you will see myriads of living animalcules. God observes every one.
“Casting all your care on Him, for He careth for you.” “He” and “you!”
III. The storms of life are proportioned to His people’s strength.
“In measure.” (See outlines The Afflictions of God’s People and The
Discipline of Sin, pp. 290, 291.) A Jew never exercised greater care and
exactitude in weighing out his gold and diamonds than does God while
meting out trials to His people. “Grace to help in time of need;” yea,
and storms equal to our strength. We do not know how much our
strength is. One man over-estimates his strength, another under-
estimates it. “But He knoweth our frame.” “God is faithful, who will not
suffer you to be tempted above that ye are able” (H. E. I. 179–188, 3675–
3695).
In various ways He maintains the merciful proportion of the storm to
the strength. 1. He does so sometimes by sending the lesser storms
before the greater. Jacob at Bethel was unable to undergo the trials of
Jacob at Mahanaim. By the time he reached the latter place, he had
become a prince, an Israel. Carrying the least burden prepares a man
for carrying the greatest (Hercules and the ox). 2. Sometimes by
sending the heaviest first. The man may then be in the fulness of his
vigour, or in spirit he may be so contumacious that some rough
handling may be necessary to bring his pride into subjection. 3. By
removing one trial before another comes. Poverty is taken away before
ill-health sets in. “He stayeth His rough wind.” 4. By sending each one
in its time. “It could not have come at a worse time.” Who says so? “If it
had happened at another time, it would have been easier to bear.” That
may be so, but would it have been as profitable? It was necessary for
you to feel. Less suffering would not have sufficed for that end.
IV. The storms of life promote purposes of wisdom and love.
1. The Lord sometimes orders trials as chastisements. It is not always so;
we are too apt to explain everything as chastisement. But God has
promised to correct (Jer. xxx. 11), and it is the promise of a father, not
the threatening of a judge. (1.) Sometimes one correction prevents
many more. (2.) When the Lord sends trials in the way of correction,
He graciously gives His children the reasons for thus dealing with
them. “The iniquity which he knoweth” (1 Sam. iii. 13). What father
would correct a child without explaining to him what it was for? And
what correction would benefit the saints while ignorant of the object in
view? Possibly the neighbours may not know, but he has himself a
private account with God. Hence arises a consequent duty (H. E. I.
144). (3.) When God thus sends trials, they are corrections, and not
merely punishments; manifestations not of vengeance, but of His love.
A gardener uses the pruning-knife only for the good of the fruit-
bearing trees in his garden. God’s corrections are designed only to take
away the sin of His people (see ver. 9, and Zech. xiii. 9; H. E. I. 56–74).
2. The Lord sometimes orders trials as exhibitions of the graces of His
people. The tempest which beat upon Job was not corrective, though he
thought so while it lasted (Job x. 2, xiii. 24). The trial brought out into
view his trust in God: “Though He slay me, yet will I trust in Him.” The
Lord’s purpose was to prove that Job was “a perfect and an upright
man” (H. E. I. 91–98).
3. Storms are sometimes preventive. A fiery trial is approaching; the
man is in danger, for he is too weak to withstand it; by a lesser trial he
is withdrawn from it. Two ships are drawing near in a fog; they are
making towards each other at a perfect angle. The top-mast of one is
blown down; the men on deck bemoan the misfortune; but it was the
means of slackening the pace of the vessel, and so prevented a
collision. A man is sometimes laid on a bed of sickness to save his life
—to save his soul!
4. Storms sometimes prepare men for nobler work. Moses, after being
brought up in the lap of luxury, is watching the flock forty years in
Midian. All the learning of Egypt is lost in a shepherd. Nay! Moses
requires a double education, for he has a duplicate work to perform—
appearing before Pharaoh in the palace, and leading Israel through the
wilderness. E.g., what good can a preacher do, if he has no experience
of his own? (Ps. li. 12, 13; 2 Cor. i. 3–6; H. E. I. 101–108, 2464, 2465).
Some one may say that he has no knowledge of storms from
experience. Wait! Peradventure thou shalt know. Should they come,
bow. Nothing breaks, if it bends.—Gweithiau Rhyddieithol, pp. 78–81,
by the late William Ambrose of Portmadoc. Translated from the Welsh
by the Rev. T. Johns of Llanelly.

The Great Trumpet.

xxvii. 13. And it shall come to pass in that day, &c.


This prophecy was literally fulfilled (Ezra i.); but it has a wider
meaning, and this also it shall be fulfilled.
I. The greatness of the Gospel. “The great trumpet.” 1. It is designed for
the world. When liberty was proclaimed for the slaves of the West
Indies, the slaves of America remained in bondage. When the slaves of
America were liberated, the bondmen in Cuba, Peru, &c., were not set
free. But here is a blessing for the whole world. “Which shall be to all
people, . . . a light to lighten the Gentiles” (Luke ii. 10, 32). One side of
the earth can only enjoy the rays of the sun at the same time; but this
“light” shall shed its rays on the whole world. 2. It is designed for the
world in its most important interests. There are inventions and
scientific discoveries—such as the steam-engine, &c.—which are
valuable to the whole world. But they are valuable only in regard to the
present life. But the Gospel meets the wants of the soul, and concerns
the endless life beyond. 3. It is so great that all other things in the world
are small in comparison with it; trade, learning, &c. 4. It is so great that
it bestows greatness upon everything it touches. Upon oratory, although
it is independent of excellency of speech. Upon any country in which it
is proclaimed and accepted; e.g., Great Britain, America. Under its
shelter liberty, learning, &c., flourish (H. E. I. 1124–1132).
II. The ministry of the Gospel. “The great trumpet shall be blown.”
What is the good of a trumpet without some one to blow it? (Rom.
x. 14).
1. Who is to blow it? Not angels (Heb. ii. 5). The law was given by the
ministry of angels; by them the trumpet was blown on Mount Sinai
(Acts vii. 53). But they recognise that the trumpet of the Gospel is to be
blown by men (Acts v. 20, x. 31, 32). This treasure is in earthen vessels.
Gideon’s Lamps. Men are better than angels for this purpose. This is
proved by the fact that God ordered it so. But there are other minor
satisfactory arguments, such as: (1.) The danger of glorifying the
missionary above the mission. (2.) The angels’ disadvantages. They lack
the necessary experience. Blessed lack, in all other respects! They have
never been contaminated by sin, and hence know not how to speak to
the heart of the sinner. By men the trumpet is now being blown, and
will be blown to the end of time. The trumpeters are falling, ministers
are dying, but the ministry is alive!
2. How is it to be blown? (1.) Clearly (1 Cor. xiv. 8). If the promises are
proclaimed, care must be taken to show to whom they belong. So with
the threatenings, &c. (2.) Vigorously. It must be done thoroughly, or
not at all. (3.) Bravely (Eph. vi. 19). The question is not what will “take,”
what is popular, what would please the masses, but “What saith the
Lord?”
III. The objects of the ministry. “They which were ready to perish.”
1. Pagans are such (Rom. i.) “Them which sat in the region and shadow
of death” (Matt. iv. 16). 2. Every unconverted sinner. They are all to be
addressed as those who are “ready to perish.” The matter cannot be
compromised because there are seat-holders, contributors, &c. Your
kindness shall not prevent our blowing from the trumpet the tones you
need to hear.
IV. The success of the Gospel. “And they shall come which were ready
to perish in the land of Assyria, and the outcasts in the land of Egypt,
and shall worship the Lord in the holy mount at Jerusalem.” 1. Whence
shall they come? From the Pharisaical hiding-places, the quicksands of
excuses, &c. They are bound in the chains of slavery; but “they shall
come!” This is as certain as the deliverance from Babylon. Take us your
harps and strike them! 2. How will they come? Weeping. Without delay.
Confidently. 3. Whither and to whom will they come? (1.) To Christ;
they cannot live without Him. (2.) To His house.
Applications.—1. Thousands have come; will you? 2. God has another
trumpet.—Gweithiau Rhyddiethol (pp. 174–176), by the late Rev. W.
Ambrose, Portmadoc. Translated from the Welsh by the Rev. T. Johns,
Llanelly.

Rejecters of the Gospel Admonished.

xxviii. 12. To whom He said, This is the rest wherewith ye


may cause the weary to rest; and this is the refreshing: yet
they would not hear.
Isaiah was one of the most eloquent of preachers, yet he could not win
the ears and hearts of those to whom he spoke. He spoke more of Jesus
Christ than all the rest of the prophets, yet the message of love was
treated as though it were an idle tale. His doctrine was clear as the
daylight, yet men would not see it (chap. liii. 1). It was not the fault of
the preacher that Israel rejected his warnings: all the fault lay with the
disobedient and gainsaying nation. The people to whom he spoke so
earnestly were drunken in a double sense:—
1. They were overcome with wine (vers. 7, 8). How is it likely that the
truth shall enter an ear which has been rendered deaf by this degrading
vice? How is the Word of God likely to operate upon a conscience that
has been drenched and drowned by strong drink? Flee from this
destroyer before your hands are made strong and you are hopelessly
fettered by the habit.
2. They were also intoxicated with pride. Their country was fruitful,
and its chief city, Samaria, stood on the hill-top, like a diadem of
beauty crowning the land, and they delighted in it. Among them were
many champions whose strength sufficed to turn the battle to the gate,
therefore they hoped to resist every invader, and so their hearts were
lifted up. Moreover, they said, “We are an intelligent people; we are
men of cultured intellect, instructed scribes, and we do not need
persons like Isaiah to weary us with the ding-dong of ‘precept upon
precept, line upon line,’ as if we were mere children at school. Besides,
we are good enough. Do we not worship our God under the form of the
golden calves in Dan and Bethel? Do we not respect the sacrifice and
the holy days?” So spoke the more religious of them, while the rest
gloried in their shame. Being intoxicated with pride, it was not likely
that they would hear the message of the prophet who made them turn
from their evil ways. Pride is the devil’s drag-net, in which he taketh
more fishes than in any other, except procrastination.
The two forms of drunkenness are equally destructive. Whether body
or soul be intoxicated, mischief will surely come of it. Let us not get
drunk with pride because we are not drunkards; for if we are so vain
and foolish, we shall as certainly perish by pride as we should have
done by drink.
I. The excellence of the Gospel as it is set forth in the passage before us.
This Scripture does not allude to the Gospel primarily, but to the
message which Isaiah had to deliver, which was in part the command
of the law and in part the promise of grace: but the same rule holds
good of all the words of the Lord; and indeed any excellence which was
found in the prophet’s message is found yet more abundantly in the
fuller testimony of the Gospel in Christ Jesus.
1. The excellence of that Gospel lies, first in its object. For
(1.) It is a revelation of rest. Christ’s ambassadors are sent to proclaim
to you that which shall give you ease, peace, quiet, rest. It is true that
we have to begin with certain truths that disturb and distress; but our
object is to dig out the foundation into which may be laid the stones of
restfulness. The object of the Gospel is not to make men anxious, but
to calm their anxieties; not to fill them with endless controversy, but to
lead them into all truth. The Gospel gives rest of conscience, by the
complete forgiveness of sin through the atoning blood of Christ; rest of
heart, by supplying an object for the affections worthy of their love;
and rest of intellect, by teaching it certainties which can be accepted
without question. Our message does not consist of things guessed at by
wit, nor evolved out of men’s inner consciousness by study, not
developed by argument through human reason; but it treats of
revealed certainties, absolutely and infallibly true, upon which the
understanding may rest itself as thoroughly as a building rests upon a
foundation of rock. The Word of the Lord comes to give believing men
rest about the present by telling them that God ordereth all things for
their good; and as for the future, it brightens all coming time and
eternity with promises. The man who will hear the Gospel message,
and receive it into his soul, shall know the peace of God, which passeth
all understanding, and shall keep his heart and mind by Jesus Christ.
(2.) It is the cause of rest. “This is the rest wherewith ye may cause the
weary to rest.” The Gospel of our salvation is not only a command to
rest, but it brings the gift of rest within itself. Let the Gospel be
admitted into the heart, and it will create a profound calm, hushing all
the tumult and strife of conscience, removing all apprehensions of
Divine wrath, stilling all rebellion against the supreme Will, and so
working in the spirit by the energy of the Holy Ghost a deep and
blessed peace.
(3.) This rest is especially meant for the weary. “This is the rest
wherewith ye may cause the weary to rest.” Oh, ye that are weary with
the round of worldly pleasure, worn with ambition, fretted with
disappointment, embittered by the faithlessness of those you trusted
in, come and confide in Jesus and be at rest. Here is the rest, here is the
refreshing. Jesus expressly puts it: “Come unto me, all ye that labour
and are heavy laden, and I will give you rest.” Despondent and
despairing, condemned, and in your conscience cast out to the gates of
hell, yet look to Jesus and rest shall be yours.
(4.) In addition to bringing us rest, the message of mercy points to a
refreshing. “This is the rest wherewith ye may cause the weary to rest;
and this is the refreshing.” If the rested one should grow weary again,
the Good Shepherd will give him refreshing; if he wanders, the Lord
will restore him; yea, He has begun His gracious work of renewing, and
He will continue it by renewing the heart from day to day, blending the
will with His own, and making the whole man more and more to
rejoice in Him.
Now, note with peculiar joy that Isaiah did not come to these people to
talk about rest in dubious terms, and say, “There is no doubt a rest to
be found somewhere in that goodness of God of which it is reasonable
to conjecture.” No; he puts his finger right down on the truth, and he
says, “This is the rest, and this is the refreshing.” Even so we at this day,
when we come to you with a message from God, come with definite
teaching; we proclaim in the name of God that whosoever believeth in
Christ Jesus hath everlasting life: this is the rest, and this is the
refreshing.
Nor did he preach a rest of a selfish character. They say we teach men to
get peace and rest for themselves, and make themselves comfortable,
whatever becomes of others. They know better, and they forge these
falsehoods because their heart is false. Are we not always bidding men
look out from themselves, and love others even as Christ has loved
them? We abhor the idea that personal safety is the consummation of a
religious man’s desires, for we believe that the life of grace is the death
of selfishness. This is one of the glories of the Gospel, that “this is the
rest wherewith ye may cause the weary to rest.” Get rest yourself, and
you will soon cause other weary minds to rest. That secret something
which your own heart possesses shall enable you to communicate good
cheer to many a weary heart, and hope to many a desponding mind.
2. The other excellence of the Gospel of which I shall speak at
this time lies in its manner.
(1.) It comes with authority. The Gospel does not pretend to be a
speculative scheme or a theory of philosophy which will suit the
nineteenth century, but will be exploded in the twentieth. No; it comes
to men as a message from God, and he that speaks it aright does not
speak it as a thinker uttering his own thoughts; but he utters what he
has learned, and acts as God’s tongue, repeating what he finds in God’s
Word by the power of God’s Spirit.
(2.) It was delivered with great simplicity. Isaiah came with it “precept
upon precept, line upon line, here a little and there a little.” It is the
glory of the Gospel that is so plain. If it were so profound that we must
take a degree at a university before we could comprehend it, what a
miserable Gospel it would be for mocking the world with! But it is
Divinely sublime in its simplicity, and hence the common people hear
it gladly. As the verse seems to imply, it is fitted for those who are
weaned from the breast; those who are little more than babes may yet
drink in this unadulterated milk of the Word. Many a little child has
comprehended the salvation of Jesus Christ sufficiently to rejoice in it.
I bless God for a simple Gospel, for it suits me, and thousands of others
whose minds cannot boast of greatness or genius. It equally suits men
of intellect, and it is only quarrelled with by pretenders. A man who
really has a capacious mind is usually childlike, and, like Sir Isaac
Newton, is glad to sit at Jesus’ feet. Great minds love the simple Gospel
of God, for they find rest in it from all the worry and the weariness of
questions and of doubts.
(3.) It is taught us by degrees. It is not forced home upon men’s minds
all at once, but it comes “precept upon precept, line upon line, here a
little and there a little.” God does not flash the everlasting daylight on
weak eyes in one blaze of glory, but there is at first a dim dawn, and the
soft incoming of a tender light for tender eyes, and so by degrees we
see.
(4.) The Gospel is repeated. If we do see it at once, it comes again to us,
for it is “precept upon precept, line upon line, here a little and there a
little.” From morning to morning, from Sunday to Sunday, book after
book, by text after text, by spiritual impression after spiritual
impression, the Divine gentleness makes us wise unto salvation.
(5.) It is brought home to us in ways suitable to our capacity. It is told
to us, as it were, with stammering lips (see ver. 11), just as mothers
teach their little children in a language all their own. In much of the
Bible, especially in the Old Testament, God condescends to lay aside
His own speech and talk the language of men. He bows to us and tells
us His mind in types and ordinances, which are a sort of child-language
fitted to our capacity. If you do not understand the Word of God, it is
not because He does not put it plainly, but because of the blindness of
your heart and the besotted condition of your spirit. Take heed that
you are not drunken with the wine of pride, but be willing to learn; for
God Himself hath not darkened counsel by mysterious words, but He
has put His mind before you as plainly as the sun in the heavens.
“Precept upon precept, line upon line, here a little and there a little.”
II. The objections which are taken to the Gospel.
1. They are most wanton. Men object to that which promises them rest!
Above all the things in the world this is what our troubled spirits need.
Oh, the intense folly of men, that when the Gospel sets rest before
them they will not hear it, but turn upon their heel. There is no system
of doctrine under heaven that can give quiet to the conscience of men,
quiet that is worth having, except the Gospel; and there are thousands
of us who bear witness that we live in the daily enjoyment of peace
through believing in Jesus, and yet our honest report is not believed;
nay, they will not hear the truth.
2. Objections against the Gospel are wilful, even as it is here said, “This
is the refreshing, yet they would not hear.” When man say they cannot
believe the Gospel, ask them whether they will patiently hear it in all
its simplicity. No, they say, they do not want to hear it. The Gospel is so
difficult to believe; so they say. Will they come and hear it preached in
its fulness? Will they read the Gospels for themselves carefully? Oh,
no; they cannot take the trouble. Just so. But a man who does not want
to be convinced must not blame anybody if he remains in error, nor
wonder that objections swarm in his mind.
3. Such objections are wicked, because they are rebellion against God
and an insult to His truth and mercy. If this Gospel be of God, I am
bound to receive it: I have no right to cavil at it, nor raise questions,
philosophical or otherwise. It is mine just to say, “Does God say this
and that? Then it is true, and I yield to it. Does the Lord thus set before
me a way of salvation? I will run in it with delight.”
4. These people raised objections that were the outgrowth of their
pride. They objected to the simplicity of Isaiah’s preaching. They said,
“Who is he? You should not go to hear him; he talks to us as if we were
children. Besides, it is the same thing over and over again. You may go
when you like, he is always harping on the same string.” Have you not
heard folks say in these days concerning a true Gospel preacher, that he
is always preaching about sovereign grace, or the blood of Christ, or
crying out, “Believe, believe, and you shall be saved”? They sneer and
say, “It is the old ditty over and over again.” The passage translated
“precept upon precept, line upon line,” was uttered in ridicule, and
sounded like a ding-dong rhyme with which they mocked Isaiah. The
words were intended to caricature the preacher; though they do not
suggest the idea when translated, they do suggest it readily enough in
the Hebrew. There are people now living who, when the Gospel is
plainly and simply preached, exclaim, “We want progressive thought;
we want”—they do not quite know what they do want. Too many wish
for a map to heaven so mysteriously drawn that they may be excused
from following it. Multitudes prefer the Gospel shrouded in a mist;
they love to see the wisdom of man shut out the wisdom of God. This
was the style of objection current in Israel’s day, and it is fashionable
still.
III. The Divine requital of these objectors.
1. The Lord threatens them with the loss of that which they despised. He
has sent them a message of rest and they will not have it, and therefore
in the 20th verse He warns them that they shall have no rest
henceforth: “For the bed is shorter than that a man can stretch himself
on it; and the covering narrower than that he can wrap himself in it.”
All those who wilfully reject the Gospel and take up with philosophies
and speculations will be rewarded with inward discontent. Ask the
preachers of that kind of doctrine whether they themselves have found
an anchorage, and as a rule they will answer, “No, no; we are in pursuit
of truth; we are hunting after it, but we have not reached it yet.” They
are never likely to reach it, for they are on the wrong track. The Gospel
was made to rest conscience, soul, heart will, memory, hope, fear, yes,
the entire man; but when men laugh at all fixity of belief, how can they
be rested? This is the condemnation of the unbeliever, that he shall
never find a settlement, but, like the wandering Jew, shall roam for
ever. Leave the Cross, and you have left the hinge of all things, and
neglected the one sure corner-stone and fixed foundation, and
henceforth you shall be as a rolling thing before the whirlwind.
2. They shall be punished by a gradual hardening of heart. They said
that Isaiah’s message was “precept upon precept, line upon line, here a
little and there a little,” and justice answers them, “Even so it shall be to
you a thing despised and ridiculed, so that you will go farther away
from it; you will fall backward and be broken, and snared and taken”
(ver. 13). A fall backward is the worst kind of fall. If a man falls forward,
he may somewhat save himself and rise again; but if he falls backward,
he falls with all his weight and is helpless. Those who stumble at
Christ, the sure foundation-stone, shall be broken. When oppressors
hope to retrieve their position, they find themselves snared by their
habits, entangled in the net of the great fowler, and taken by the
destroyer. This downward course is followed full often by those who
begin cavilling at the simple Gospel; they cavil more and more, and
become its open enemies to their eternal ruin.
3. This is to be followed by a growing inability to understand. “For with
stammering lips and another tongue will He speak to this people.”
Since they would not hear plain speech, God will make simplicity itself
to seem like stammering to them. Men that cannot endure simple
language shall at last become unable to understand it. If men will not
understand, they shall not understand. A man may shut his eyes so
long that he cannot open them. In India many devotees have held up
their arms so long that they can never take them down again. Beware
lest an utter imbecility of heart come upon those of you who refuse the
Gospel.
Lastly, this warning is given to those who object to the Gospel, that
whatever refuge they choose for themselves shall utterly fail them. Thus
saith the Lord, “Judgment will I also lay to the line, and righteousness
to the plummet: and the hail shall sweep away the refuge of lies, and
the waters shall overflow the hiding-place.” Down come the great
hailstones dashing everything to shivers, the threatenings of God’s
Word breaking to pieces all the false and flattering hopes of the
ungodly. Then comes the active wrath of God like an overwhelming
flood to sweep away everything on which the sinner stood, and he, in
his obstinate unbelief, is carried away as with a flood into that utter
destruction, that everlasting misery, which God has declared shall be
the lot of all those who refuse the living Christ.—C. H. Spurgeon:
Metropolitan Tabernacle Pulpit, No. 1593.

False Refuges.

xxviii. 18. Your covenant with death shall be disannulled.


Like the sinners spoken of in this chapter, most sinful men say in effect,
“We have made a covenant with death,” &c. (ver. 15).
I. That he may escape the dreaded consequences of sin, the
troubled sinner seeks a refuge. He flees—1. From the voice of reason.
The presence of a reasoning power in man is incompatible with the
practice of sin. This is seen in the fact that when sinners can be
brought to think, they at once admit themselves to be wrong. The
moment a man commences to think about sin, that moment he
becomes aware that it will not bear thinking about. It is because a
sinful life is an unthinking life that God’s invitations to sinners are
invitations to reason (chap. i. 18; Ps. l. 22–23). 2. From an accusing
conscience. The authority of conscience is supreme, and no man can
sin without feeling its sting. To escape remorse, which is conscience at
work, men seek a refuge. 3. From an offended God. Sin is offensive to
God’s holiness; for being pure, He must hate impurity. Because sinners
are conscious that they have rendered themselves obnoxious to God,
they seek a refuge. 4. From a broken law. In obedience to law there is
safety, right, and happiness; while in disregarding law there is nothing
but disaster. And from the consequences of the broken law—the
broken law of God written on the heart, proclaimed in Nature, revealed
in the Bible—the sinner tries to hide. 5. From an endless future. This
more than anything else terrifies sinners and drives them to seek
shelter.
II. Sinners, blindly infatuated, seek a refuge in the wrong objects.
They make a covenant with death and an agreement with hell. The
terms “death” and “hell” stand for the whole class of false securities in
which men seek shelter by making a covenant and agreement with
them. 1. Unbelief is one of the most modern refuges of sin. When men
can blot out of the universe the idea of God, quench the sense of moral
responsibility, remove the belief in immortality, persuade themselves
that there is no other world, that death is an eternal sleep, that heaven
is only an air-castle, and hell a mere chimera, they may then indulge in
evil to their hearts’ content. 2. Superstition is another. Not in open
unbelief, but under the cover of a false religion others seek to shelter.
Unable to shake off belief in God and in a spiritual world, they search
for some system which will at once allow a profession of religion and a
practice of wickedness. Nor are such systems wanting, nor are they
without disciples. Romanism offers indulgences for gold and pardons
for peace, and thus provides a refuge for the stronger in pocket than in
brain. 3. Annihilation is another. According to some, such is the
awfulness of the thought of extinction of being, that men revolt from
it. Establish it that when sinners die they cease to live, and what better
refuge for sin is possible, and what other is needed? Sinful men will
soon say, “Let us eat and drink, for to-morrow we die.” 4. Excess is
another. When the previous ones have failed to give comfort, the
sinner rushes madly into excess. The drunkard seeks in increased
intemperance to drown the sorrow his indulgence has occasioned.
5. Indifference is the last. This is the only comfort some men can find in
their career of evil. But indifference is impossible without a denial of
human responsibility. Sad indeed must the condition of human nature
be when brought to this.
III. The refuges so confidently trusted in are utterly insecure.
1. Because they are incompatible with the real need of man. Only that
can be conducive to man’s safety which meets man’s need. No human
need is met by infidelity, or by superstition, or by annihilation, or by
indulgence, or by indifference. Any one of these, tested by this
argument drawn from human necessities, will be found a refuge of lies.
2. Because they are at variance with human instincts. Instinctively men
believe in a Divine existence, in moral accountability, and in
immortality. 3. Because they contradict human experience. They have
all been tried, and as often as they have been tried they have been
found false. 4. Because they are opposed to the teaching of revelation,
both natural and Biblical. Nature proclaims loudly against all sin-
sought refuges. The teaching of Nature and the Bible is that man is
incompetent to provide for his own security, and that God only, in the
exercise of His Divine prerogative, can provide for sinners the security
they need.
IV. By Divine appointment the refuges so madly sought shall be
totally destroyed. “Your covenant with death shall be disannulled.”
1. By consequence of their inherent character. They are “refuges of lies,”
and necessarily all refuges built on lies must perish. 2. By necessity of
strict justice. “Judgment will I lay to the line, and righteousness to the
plummet” (ver. 17). 3. By the exertion of Almighty power. “And the hail
shall sweep away the refuge of lies, and the waters shall overflow the
hiding-place.”
Conclusion.—God has mercifully provided a true refuge. He only cuts
off the false that He may exhibit the true. “Behold, I lay in Sion for a
foundation a stone,” &c. (ver. 16).—William Brooks: Study and the
Pulpit, New Series, vol. i. pp. 413–416.

Some Aspects of Ministerial Duty.

xxx. 7. Therefore have I cried concerning this, Their


strength is to sit still.
Jerusalem and Judah were threatened by Sennacherib with dangers and
desolations. This people’s sin, for which they were reproved by Isaiah,
was their trusting to the Egyptians; they were all in a hurry to obtain
help from them, without seeking counsel of God and resting upon
Him. Isaiah saw that the help of the Egyptians would be worthless to
them, and therefore he counselled them to “sit still,” trusting in the
power, providence, and promise of God, from whom too much cannot
be expected.
I. Notice the prophet’s intermeddling in this important matter.
He publishes God’s mind concerning it. It is the duty of ministers to
meddle sometimes in public matters, whether in Church or State; they
are to show Jacob their sins, and Israel their transgressions. This is a
part of ministers’ work, to testify against sin in all. Christ was the light
of the world; and they should be like their Master, testifying against all
works of darkness. True, the world quarrels with the servants of God
because they bear testimony against its sins; and on this account many
ministers who have some light, put their light in prison: “They hold the
truth in unrighteousness.” They do this by not bearing witness against
public wrongs, and the sin and defection of statesmen. But it was a
gracious expression of a graceless Cain, “Am I my brother’s keeper?”
“What am I concerned with the souls or the sins of others? What am I
concerned with the public evils of the day I live in?” True religion
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookluna.com

You might also like