0% found this document useful (0 votes)
54 views

Python Distilled Developer s Library 1st Edition David Beazley download

Ebook installation

Uploaded by

theopoaafaq
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
0% found this document useful (0 votes)
54 views

Python Distilled Developer s Library 1st Edition David Beazley download

Ebook installation

Uploaded by

theopoaafaq
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/ 81

Python Distilled Developer s Library 1st Edition

David Beazley install download

https://ebookmeta.com/product/python-distilled-developer-s-
library-1st-edition-david-beazley/

Download more ebook from https://ebookmeta.com


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

Python Language and Library 1st Edition Srikanth


Pragada

https://ebookmeta.com/product/python-language-and-library-1st-
edition-srikanth-pragada/

The Well-Grounded Python Developer - MEAP Version 5


Doug Farrell

https://ebookmeta.com/product/the-well-grounded-python-developer-
meap-version-5-doug-farrell/

Java Platform Standard Edition Security Developer s


Guide Oracle

https://ebookmeta.com/product/java-platform-standard-edition-
security-developer-s-guide-oracle/

Supply Chain: The Insights You Need From Harvard


Business Review Harvard Business Review

https://ebookmeta.com/product/supply-chain-the-insights-you-need-
from-harvard-business-review-harvard-business-review/
Incorporating Weight Management and Physical Activity
Throughout the Cancer Care Continuum Proceedings of a
Workshop 1st Edition And Medicine Engineering National
Academies Of Sciences
https://ebookmeta.com/product/incorporating-weight-management-
and-physical-activity-throughout-the-cancer-care-continuum-
proceedings-of-a-workshop-1st-edition-and-medicine-engineering-
national-academies-of-sciences/

Criminal law elements Sixth Edition. Edition Penny


Crofts

https://ebookmeta.com/product/criminal-law-elements-sixth-
edition-edition-penny-crofts/

Plays Roswitha Of Gandersheim

https://ebookmeta.com/product/plays-roswitha-of-gandersheim/

Introducing Spring Framework 6 2nd Edition Felipe


Gutierrez

https://ebookmeta.com/product/introducing-spring-framework-6-2nd-
edition-felipe-gutierrez/

Magic Shifts Kate Daniels 08 3rd Edition Ilona Andrews

https://ebookmeta.com/product/magic-shifts-kate-daniels-08-3rd-
edition-ilona-andrews/
Team Titanic!: A Superhero Harem Adventure 1st Edition
Archer

https://ebookmeta.com/product/team-titanic-a-superhero-harem-
adventure-1st-edition-archer/
Python Distilled

David M. Beazley
Author of Python Essential Reference
Contents
Preface

Acknowledgments

About the Author

Chapter 1: Python Basics

Chapter 2: Operators, Expressions, and Data


Manipulation

Chapter 3: Program Structure and Control Flow

Chapter 4: Objects, Types, and Protocols

Chapter 5: Functions

Chapter 6: Generators

Chapter 7: Classes and Object-Oriented


Programming

Chapter 8: Modules and Packages

Chapter 9: Input and Output

Chapter 10: Built-in Functions and Standard


Library
Table of Contents
Preface

Acknowledgments

About the Author

Chapter 1: Python Basics


Running Python
Python Programs
Primitives, Variables, and Expressions
Arithmetic Operators
Conditionals and Control Flow
Text Strings
File Input and Output
Lists
Tuples
Sets
Dictionaries
Iteration and Looping
Functions
Exceptions
Program Termination
Objects and Classes
Modules
Script Writing
Packages
Structuring an Application
Managing Third Party Packages
Python: It Fits Your Brain

Chapter 2: Operators, Expressions, and Data


Manipulation
Literals
Expressions and Locations
Standard Operators
In-place Assignment
Object Comparison
Ordered Comparison Operators
Boolean Expressions and Truth Values
Conditional Expressions
Operations Involving Iterables
Operations on Sequences
Operations on Mutable Sequences
Operations on Sets
Operations on Mappings
List, Set, and Dictionary Comprehensions
Generator Expressions
The Attribute (.) Operator
The Function Call () Operator
Order of Evaluation
Final Words - The Secret Life of Data

Chapter 3: Program Structure and Control Flow


Program Structure and Execution
Conditional Execution
Loops and Iteration
Exceptions
Context Managers and the with Statement
Assertions and __debug__
Final Words

Chapter 4: Objects, Types, and Protocols


Essential Concepts
Object Identity and Type
Reference Counting and Garbage Collection
References and Copies
Object Representation and Printing
First Class Objects
Using None for Optional or Missing Data
Object Protocols and Data Abstraction
Object Protocol
Number Protocol
Comparison Protocol
Conversion Protocols
Container Protocol
Iteration Protocol
Attribute Protocol
Function Protocol
Context Manager Protocol
Final words: On Being Pythonic
Chapter 5: Functions
Function Definitions
Default Arguments
Variadic Arguments
Keyword Arguments
Variadic Keyword Arguments
Functions Accepting All Inputs
Positional Only Arguments
Names, Documentation Strings, and Type Hints
Function Application and Parameter Passing
Return Values
Error Handling
Scoping Rules
Recursion
The lambda Expression
Higher Order Functions
Argument Passing in Callback Functions
Returning Results from Callbacks
Decorators
Map, Filter, and Reduce
Function Introspection, Attributes, and Signatures
Environment Inspection
Dynamic Code Execution and Creation
Asynchronous Functions and Await
Final Words: Thoughts on Functions and Composition

Chapter 6: Generators
Generators and yield
Restartable Generators
Generator Delegation
Using Generators in Practice
Enhanced Generators and yield Expressions
Applications of Enhanced Generators
Generators and the Bridge to Awaiting
Final Words: A Brief History of Generators and Looking Forward

Chapter 7: Classes and Object-Oriented


Programming
Objects
The class Statement
Instances
Attribute Access
Scoping Rules
Operator Overloading and Protocols
Inheritance
Avoiding Inheritance via Composition
Avoiding Inheritance via Functions
Dynamic Binding and Duck Typing
The Danger of Inheriting from Built-in Types
Class Variables and Methods
Static Methods
A Word About Design Patterns
Data Encapsulation and Private Attributes
Type Hinting
Properties
Types, Interfaces, and Abstract Base Classes
Multiple Inheritance, Interfaces, and Mixins
Type-based Dispatch
Class Decorators
Supervised Inheritance
The Object Life Cycle and Memory Management
Weak References
Internal Object Representation and Attribute Binding
Proxies, Wrappers, and Delegation
Reducing memory use with __slots__
Descriptors
Class Definition Process
Dynamic Class Creation
Metaclasses
Built-in Objects for Instances and Classes
Final Words: Keep it Simple

Chapter 8: Modules and Packages


Modules and the import Statement
Module Caching
Importing Selected Names from a Module
Circular Imports
Module Reloading and Unloading
Module Compilation
The Module Search Path
Execution as the Main Program
Packages
Running a Package submodule as a script
Controlling the Package Namespace
Controlling Package Exports
Package data
Module Objects
Module Attribute Access
Deploying Python Packages

Chapter 9: Input and Output


Data Representation
Text Encoding and Decoding
Text and Byte Formatting
Reading Command-Line Options
Environment Variables
Files and File Objects
I/O Abstraction Layers
Standard Input, Output, and Error
Directories
The print() function
Generating Output
Consuming Input
Object Serialization
Blocking Operations and Concurrency
Standard Library Modules
Final Words

Chapter 10: Built-in Functions and Standard


Library
Built-in Functions
Built-In Exceptions
Standard Library
Final Words: Use the builtins
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 your brain. The
Essential Reference reflected that era. It was meant to be a small
book that you could take with you to write some Python code on a
desert island or inside a secret vault. Over three subsequent
revisions, the Essential Reference more-or-less evolved with this
vision of being a compact, but complete language reference—
because if you were going to code Python on vacation, why wouldn’t
you want to use all of it?
Today, more than a decade has passed since the publication of the
last edition and the Python world is much different. No longer a
niche language, Python has grown to 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 very eyes with the touch of a few keys.
If anything, the ease of information retrieval and the "bigness" of
the Python universe presents a different kind of challenge. If you’re
just trying to learn or starting to solve a new problem, it can be a bit
overwhelming to know where to begin. It can also be di˚cult to
separate the features of various tools from the core language itself.
These kinds of problems are the foundation for this book.
Python Distilled is a book about programming in Python. However,
rather than tring to document absolutely "everything" that’s possible
or has been previously done in Python, the focus is on presenting a
modern, yet curated (or distilled) core of the language. Much of this
has been informed by my years of teaching Python to scientists,
engineers, and software professionals. However, it’s also a product
of writing various software libraries, pushing the outer edges of what
makes Python tick, and learning about what’s most useful.
For the most part, the book stays focused on the topic of 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
(i.e., 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 related to editors, IDEs,
deployment, and other 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—somehow involving
millions upon millions of lines of code. Maintaining such applications
requires tooling, and design, and features, and types, and
committees, and meetings, and decisions to be made about very
important matters. Matters of such importance are too important for
this small book. Thus, they are left as an exercise for the reader.
However, the honest answer is that I don’t use Python to write such
applications—and neither should you.
In writing a book, there is always a cut-off regarding 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 remain
fun. I hope that the book not only helps you become a productive
Python programmer, but that it also captures some of the magic that
has inspired people to use Python for exploring the stars, flying
helicopters on Mars, or spraying squirrels with a water cannon in the
backyard.
Acknowledgments [This content
is currently in development.]
This content is currently in development.
About the Author [This content
is currently in development.]
This content is currently in development.
Python Basics
This chapter provides an overview of the central core of the Python
language. Topics include 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 intended 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.

Running Python
Python programs are executed by an interpreter. There are many
different environments in which the Python interpreter might run
ranging from IDEs, a browser, or a terminal window. However,
underneath all of that, the core of the interpreter is a text-based
application that can be started by typing python into a terminal
command shell such as bash. Because Python 2 and Python 3 might
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 at which you can
start typing 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
>>>

Certain environments may display a different prompt such as the


following output 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 output you see, the underlying principle is


the same. If you type a command, it runs and you’ll 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 results.
This is useful for debugging and experimentation. Many people,
including the author, even 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 the result of the
last operation in subsequent statements. This variable only gets
defined when working interactively so you don’t use it in saved
programs.
You can exit the interactive interpreter by typing quit() or the EOF
(end of file) character. On UNIX, EOF is Ctrl+D; on Windows, it’s
Ctrl+Z.

Python Programs
If you want to create a program that you can run repeatedly, put
statements in a text file such as the following:
# hello.py
print('Hello World')

Python source files are UTF-8 encoded text files that normally have a
.py su˚x. 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 remember to use UTF-8 encoding
(this is often the default in most editors, but it never hurts to check
your editor settings if you’re unsure).
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')
If you give this file execute permissions on Unix (e.g., using 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 vs 3). Be aware that execution of a program might take
place in a console window that disappears immediately after the
program completes its execution (often before you can read its
output). For debugging, it may be 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.

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 (e.g., an integer, float, string, etc.).
x = 42

Sometimes you might see a type explicitly attached to a name. For


example,
x: int = 42
The presence of a type is merely a hint to assist code readability and
for possible use 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 produce a value:
2 + 3 * 4 # -> 14

The following program shows the use of variables and expressions


by performing 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, the following output is produced:


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. However, 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 3-digit
decimal number, right aligned. '0.2f' means a floating point
number with 2 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

Arithmetic Operators
Python has a standard set of mathematical operators as shown in
Table 1. These operators have the standard meaning as they do in
most other programming languages.

Table 1: Arithmetic Operators


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 2 provide a few more


commonly used numerical operations:

Table 2: Common Mathematic Functions


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 as shown in Table 3.

Table 3: Bit Manipulation Operators

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
are represented in a 2’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 4:

Table 4: Comparison Operators

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


The and, or, and not operators can form more complex Boolean
expressions related logical truth (not to be confused with the bit-
manipulation operators above). The behavior of these operators is as
shown in Table 5.

Table 5: Logical Operators

A value is considered "false" if it is literally False, None, numerically


zero, or empty. Otherwise, it’s considered true.
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 the +, -,
*, **, /, //, %, &, |, ˆ, <<, >> operators. Python does not have
increment (++) or decrement (--) operators sometimes found in
other languages.

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, like this:


if suffix == '.htm':
content = 'text/html'
elif suffix == '.jpg':
content = 'image/jpeg'
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, you can use
a conditional expression like this:
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" since := 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 use of parentheses to surround an assignment expression is


always required.
The break statement can be used to abort a loop early. It only
applies to the inner-most 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 is used to skip the rest of the loop body and
go 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')

Text Strings
To define string literals, enclose them 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 that appears
prior to 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 such as the following:
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))

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]. This 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 6 shows a few common string methods (Note: here and


elsewhere, arguments enclosed in square brackets are optional).

Table 6: Common String Methods


Strings are concatenated with the plus (+) operator:
g = a + 'ly' # g = 'Hello Worldly'

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, strings first have 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, it is advised to use repr(s) when producing


output. repr() shows you more precise information about the 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'
>>>

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 usually
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 above the function is using break as
follows:
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 as shown in this example:
with open('out.txt', 'wt') as out:
while year <= numyears:
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 Unicode. 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 at the
keyboard. To do that, use the input() function. For example:
name = input('Enter your name : ')
print('Hello', name)

input() returns all of the typed text up to the terminating newline,


which is not included.

Lists
Lists are an ordered collection of arbitrary objects. You create a list
by enclosing values in square brackets, as follows:
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:


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 as follows:
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

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 being loaded in
order 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] contains 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.

Tuples
To create simple data structures, you can pack a collection of values
together into an immutable object known as a tuple. You create a
tuple by enclosing a group of values in parentheses like this:
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). This reflects
the fact that a tuple is best viewed as a single immutable object
consisting 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 consisting of
different 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
>>> 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 to perform this


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

When iterating over tuples, the variable _ is sometimes used to


indicate a discarded value. In the above calculation, it means we’re
ignoring the first item (the name).

Sets
A set is an unordered collection of unique objects and is 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, be aware that the order
of items can’t be predicted and that the output may vary from what’s
shown. The order might even change from run-to-run of the
interpreter.
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 }

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 sets.
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.

Dictionaries
A dictionary is a mapping between keys and values. You create a
dictionary by enclosing the keys and values, 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'

A dictionary is a useful way to define an object that consists of


named fields as shown. 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 with an expression


such as
p = prices['IBM']

Dictionary membership is tested with the in operator, as in the


following example:
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 as follows:
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 a building block 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),
('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.
Common data processing tasks such as this have often already been
implemented by library modules. For example, the collections
module has a Counter object that can be used for this same 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 some


caution is required since it looks like you might also be 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 which
actively reflects changes made to the dictionary. For example:
Other documents randomly have
different content
The Project Gutenberg eBook of The Dying
Indian's Dream: A Poem
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: The Dying Indian's Dream: A Poem

Author: Silas Tertius Rand

Release date: September 21, 2015 [eBook #50025]


Most recently updated: October 22, 2024

Language: English

Credits: Produced by Larry Harrison, Cindy Beyer, Ross Cooling


and
the online Project Gutenberg team at
ttp://www.pgdpcanada.net with images provided by
The
Internet Archives-US

*** START OF THE PROJECT GUTENBERG EBOOK THE DYING


INDIAN'S DREAM: A POEM ***
THE

Dying Indian’s
DREAM.
A POEM.

BY SILAS TERTIUS RAND,


Of Hantsport, Nova Scotia,
MISSIONARY TO THE MIC-MAC INDIANS.

(THIRD EDITION, REVISED.)

With some Additional Latin Poems.

WINDSOR, N. S.:
C. W. KNOWLES.
1881
PREFACE TO THE THIRD EDITION.

The Wigwam Scene described in the following pages, occurred at


Hantsport, Nova Scotia, in March, 1855. In the Sixth Annual Report
of the Mic-Mac Mission, in a letter written immediately after the
event, I find it thus described:
“An event of some interest has just occurred here. One of our
sick Indians, named John Paul, has just died, and was buried to-day.
I have taken from my first acquaintance with him, a great liking to
him. I have spent many an hour with him in his wigwam. He always
listened attentively to the Scriptures, and engaged readily in
religious conversation, and I have not been without hope that the
grace of God had taken possession of his heart. Efforts were made
to deter him from allowing my visits; but they were unavailing. I
never aimed so much to attack his Romish errors directly, as to dwell
upon the free salvation of the Gospel—without money and without
price. About last New Year’s Day, while I was in Halifax, I was
informed that the Romish priest had sent orders to him to leave
Hantsport, and had threatened him with all the curses of the Church
if he remained. His statement to me when I returned, was: “I won’t
leave this place till I choose. It is not in the power of any man to
keep me out of Heaven. That is a matter between God and my own
soul.” He said in Indian: “Neen alsoomse.” “I am my own master.” He
remained. He continued to listen to the Bible with attention, and to
receive my visits with kindness and respect till he died. I now
recollect that when I came to read to him, he would send the small
children away, so that we might not be disturbed. The last time I
saw him was a precious season to my own soul. It seemed easy to
speak of the Great Redeemer, and of the way of Salvation. I may say
that special prayer was made for him in the Meeting House, where a
number of christian friends were assembled on the day before he
died, holding a special prayer meeting on our own account. More
than one fervent prayer was offered up for the dying Indian. After
the meeting I returned to my own house, where I met an Indian
from John Paul’s wigwam, who informed me that the poor fellow was
near his end. “But oh,” said he, “he is wonderfully happy! He says he
is going right to heaven, and that he has already had a glimpse of
that bright happy world. He has been exhorting us all, and telling us
how easy it is to be saved. He dreamed last night that he was in
heaven. Heaven seemed to him to be an immense great palace, as
large as this world, all formed of gold. He saw there the glorious
Redeemer, surrounded by an immense Host of Saints and Angels, all
drest in white. As he entered he thought they gathered round him
and shouted: John Paul has come! John Paul has come!” The poor
fellow did not die until the following morning, and just before he
died he looked up towards heaven, and declared that he saw the
angels, and the Glory of God. He was astonished that the others
could not see what he saw. He wanted them to hold up his children,
that they might see the wonders that he himself saw. He then sank
back on his pillow and quietly expired.
It will be thus seen that the following Poem is not a work of
fiction. It aims to relate—with some license of imagination, of
course, else it would not be poetry—a plain historical fact. The
description of Paul’s skill and knowledge as a hunter, and in
managing their frail little water-crafts in a sea, is literally true of
many of the Indians, and was true of him. His peace of mind in
committing his family into the hands of God, after he found himself
disabled, having burst a blood vessel by carrying a large load, from
which he never recovered—he related to me: and this is expressed
in the prayer put into his mouth at the close, “which we did not fully
hear or share.”
It may be added that after the Poem was written, I read it to the
Indian who gave me the account of John Paul’s death, and as he
spoke the English language well, he had no difficulty in
understanding it. And he assured me that it described the scene
correctly.
I may add that the measure—or rather the utter disregard of all
regular measure—was suggested by an old poem I saw somewhere,
describing a very different scene, and the “wildness” of it appealed
to me to be just suited to a scene of the Wilderness and the
wigwam.
It will not surely be deemed a very great stretch of “poetic
license” to represent oneself as an eye- and ear-witness of a scene,
with the surroundings of which he was so familiar, and which had
been so vividly described by those who really were present.
Nor need we speculate about the cause of dreams or their
significance. No one will deny that they may be a very exact index of
the state of mind at the time, of the one who dreams. And the
earnest prayer of the writer, is, that the reader of these verses, and
himself, may be, at the time of our departure, so full of joy and
peace in believing, that whether waking or dreaming, we may
“rejoice with that joy which is unspeakable and full of glory,
receiving the end of our faith, even the salvation of our souls.”
Silas T. Rand.
Hantsport, N. S.

The Dying Indian’s Dream.

“Jesus, the vision of thy face,


Hath overpowering charms;
Scarce shall I feel Death’s cold embrace,
If Christ be in my arms.
Then when you hear my heartstrings break,
How sweet my minutes roll;
A mortal paleness on my cheek,
And glory in my soul.”—Watts.
I.

Upon his bed of clay,


Wasting away,
Day after day,
A sick and suffering Indian lay:
No lordly Chieftain he,
Of boasted pedigree,
Or famed for bravery
In battle, or for cruelty;
He was of low degree,
The child of poverty,
And from his infancy,
Inured to hardship, toil and pains;
He was a Hunter, bold and free,
Of famed Acadia’s plains.
He’d roamed at will,
O’er rock and hill,
And every spot he knew,
Of forest wide,
Of mountain side,
Of bush and brake,
Of stream and lake,
Of sunny pool and alder shade,
Where the trout and the salmon played,
Where the weeping willow wept,
Where the whistling wood-cock kept,
Where the mink and the martin crept,
Where the wolf and the wild-cat stept,
Where the bear and the beaver slept,
Where the roaring torrent swept,
Where the wandering woodman strayed,
Where the hunter’s lodge was made,
Where his weary form was laid;
Where the fish and the game abound,
Where the various kinds are found,
Every month the Seasons round:
Where beetling bluffs o’er hang the deep,
Where laughing cascades foam and leap,
Dancing away from steep to steep:
Where the ash and the maple grew,
Where the hawk and the eagle flew,
Sailing in the azure blue.
With matchless skill,
He could hunt and kill,
The moose and the carriboo,
And smoothly ride
On the rolling tide,
In the light and frail canoe;
Though in angry gusts the tempest blew,
Though the thunders roared,
And the torrents poured,
And the vivid lightnings flew;
With a noble pride,
Which fear defied,
With steady hand and true,
The fragile skiff
By the frowning cliff,
He could steadily guide,
And safely glide,
In joyful glee,
Triumphantly,
The roaring surges through.
II.

And many a weary day,


He had toiled away,
In his own humble home,
At basket, bark, and broom,
To gain the scanty fare,
Doled out to him grudgingly, where
His ancient sires,
Kindled their fires,
And roamed without control,
Over those wide domains,
Rocks, rivers, hills, and plains,
In undisputed right, lords of the whole.
But ah! those days were gone,
And weeks and months had flown,
Since dire disease had laid him low;
Nor huntsman’s skill,
Nor workman’s will,
In want, in danger, or alarm,
Could nerve his powerless, palsied arm,
Or bend his useless bow.
But God was there,
And fervent prayer,
To Heaven ascended,
And sweetly blended
With angel’s song,
From Seraph’s tongue;
And Joy was there, and Hope, and Faith,
Triumphing over pain and death;
The Light of Truth around him shone,
Auspicious of the brighter dawn;
He trusted in the living God,
As washed in Jesus’ precious blood:
No dread of death or priestly power,
Could shake him in that fearful hour,
Nor tyrant’s rod.
The fluttering breath from his palsied lung,
No utterance gave to his quivering tongue;
But still his ear
Was bent to hear
The Words of Truth and Love;
His flashing eye
Glanced toward the sky,
And he whispered, “I shall die;
But God is Love; There’s rest above.”
III.

He slept! the dying Indian slept!


A balmy peace had o’er him crept,
And for the moment kept
His senses steeped
In calm and sweet repose,—
Such as the dying Christian only knows.
Consumption’s work was done;
Its racking course was run;
His flesh was wasted, gone;
He seemed but skin and bone,
A breathing skeleton—
Deep silence reigned—no sound,
Save the light fluttering round
Of scattered leaflets, found
Upon the frozen ground,
And the gently whispering breeze,
Soft sighing through the trees,
Was in the wigwam heard;
The voice of man, and beast, and bird,
Were hushed—save the deep drawn sigh,
And the feeble wail of the infant’s cry,
Soothed by the mother’s sobbing lullaby,
And bursts of grief from children seated nigh,
Waiting to see their father die.
Kindred and friends were there,
Gathered for prayer,
To soothe the suffering and the grief to share;
And Angel Bands were near,
Waiting with joy to bear
A ransomed spirit to that World on high,
That “Heaven of joy and love, beyond the Sky.”
IV.

He dreamed! the dying Indian dreamed!


Flashes of Glory round him gleamed!
A bright effulgence beamed
From on high, and streamed
Far upward and around; it seemed
That his work on earth was done,
That his mortal course was run,
Life’s battle fought and won;
That he stood alone,
Happy, light and free,
Listening to sweetest melody,
And softest harmony,
From the etherial plains,
In loud extatic strains,
Such as no mortal ear,
Could bear, or be allowed to hear.
When suddenly to his wondering eyes,
Upstarting to the skies,
A glorious Palace stood;
All formed of burnished gold,
Solid, of massive mould,
The bright Abode
Of the Creator God!
Ample, vast and high,
Like Earth, and Sea, and Sky,
The Palace of the King of kings,
Where the flaming Seraph sings,
Waving his golden wings;
Where the ransomed sinner brings,
Honour and glory to the Eternal Son,
Casting his dazzling crown,
In lowly adoration down,
Before the blazing Throne,
Of the Eternal Three in One.
But oh! what rapturous sounds!
A shout through Heaven resounds!
Myriads of happy spirits, robed in white,
More pure and bright
Than the noonday light,
Are standing round the Throne,
Of the Eternal One.
Every eye upon him turns,
Every breast with rapture burns,
And trembles the lofty Dome,
As they shout him welcome home—
“John Paul has come! John Paul has come!”
V.

He woke! the dying Indian woke


Opened his eyes and spoke:
A heavenly radiance broke
From his bright beaming eye,
And with a loud exultant cry,
And clear ringing voice,
In the soft accents of his native tongue,
And in glowing imagery,
Suited to the theme,
Like that of the Immortal Dreamer’s Dream,
In Bedford’s mystic “Den,” whose fame,
He’d never heard, nor knew the “Pilgrim’s” name,—
Or that Sublimer Song,
By John of old, in Patmos’ Prison sung,
To the Celestial Throng;—
Whose dazzling visions of the Throne,
He’d never read, or heard, or known;
He told the visions of his head,
While slumbering upon his bed;
And spoke of those unutterable joys
Prepared on high,
Beyond the sky,
For sinners saved in Jesus when they die.
VI.

With mute amaze,


And earnest gaze,
Seated round his cot
Entranced, and to the spot
Enchained, we listen to the story,
Catching glimpses of the glory;
As though the echoing roll
From the Eternal Hill,
In soft vibrations broke,
Upon our senses while he spoke,
Sending through every soul,
A deep unutterable thrill!
“Oh! I have been in Heaven!”
To me it has been given
To see the Throne of Light,
And Hosts of Angels bright,
And Ransomed Spirits robed in white;
They knew my name,
And who I am,
And whence I came;
I heard them loud through heaven proclaim:
“Make room! make room!
John Paul has come! John Paul has come!”
Bear the glad tidings far
As the remotest star!
Let every tongue
The shout prolong!
Sound the Redeemer’s praise,
In loudest, loftiest lays!
Your noblest Anthems raise
To everlasting days,
To Him who bought him
With His precious blood;
To Him who brought him
To this bright Abode
Of perfect blessedness,
And everlasting peace,
“The Bosom of his Father and his God.”
VII.

“Oh! I shall surely reach that place,


Through matchless grace!
One moment more below
I linger, then I go,
From this dark world of woe,
Where floods of sorrow overflow,
To those bright beauteous Plains,
Where Glory everlasting reigns:
That Land of heavenly Rest,
Among the Pure and Blest,
Where Jesus is—where I
Shall never sin again or sigh;—
In that bright World on high,
There are no stains
Of sin, and no remains
Of sorrow, sighs, and pains;
But pure and perfect happiness,
And royal robes of heavenly dress,
I shall eternally possess:
Where holiness and peace
Never to cease,
But ever to increase,
Abound—ah yes! this Bliss,
Which I shall there possess,
In all its glorious blessedness,
Forever and forever reigns,
O’er all those wide extended plains.”
“Oh! I must meet you there,
My brothers! you must share
That Blessedness with me,
So wonderful, so free;
That Mansion in the skies,
Not bought with gold or price,
But with the precious blood,
Of Christ, the Lamb of God,
Who died on Calvary’s bloody tree,
In pain, and bitterest agony,
To set us guilty sinners free,
From all our sin and misery.
Oh! wondrous Love! that we, even WE,
Despised, degraded, though we be,
In wretchedness and poverty,
May find Redemption in his Name,
That rich Inheritance to claim,
With yonder blood-washed company,
All robed in spotless purity,
And Joy, to all eternity.”
“Oh! listen to the Great Redeemer’s voice,
Receive His Word, make Him your choice,
Trust in His Name, and in His Love rejoice,
Forsake all sin, repent, and be forgiven,
Then I shall meet you all again in Heaven.”
VIII.

He ceased—his word, no longer heard,


Through every chord, our souls had stirred.
The glistening eye, gave back reply,
Then rose on high, the heart-felt cry:
Lord, grant that I, when called to die,
May thus be blessed, from pain released,
As Heavenly Guest, with Thee to feast:
Oh! be Thou near, my soul to cheer,
That doubt and fear, may disappear,
That joy and rest, may fill my breast,
That visions bright, of heavenly light,
Like his to-night, may cheer my sight.
Should quiet sleep my senses keep,
And Fancy leap the pathless steep,
Where whirl the streams of airy dreams,
With glittering gleams, of heavenly beams,—
Oh! may I in fit frame be found,
To dream of “Angels hovering round,”
And “leave the world without a tear,
Save for the friends I hold so dear.”
Or should fierce pains forbid to sleep,
May I amid the anguish deep,
When shuddering death-chills o’er me creep,
And friends around me mourn and weep,
Be buoyed above the waves’ wild sweep,
Where bursting billows roar and leap;
And hear the ‘whispering angels’ say,
“Sister Spirit, come away;”
And borne on Faith and Fancy’s wing,
Still hear them as they shout, and sing,
“My ears with sounds seraphic ring,”
My soul through all its mystic springs,
Thrill like a Harp’s harmonious strings,
Defiance at the foe to fling;
That I may shout, exult, and cry:
“Lend, lend, your wings! I mount, I fly!”
“Oh! Death, where is thy victory!
Oh! Death, where is thy sting!”
My faith has triumphed over thee,
A conquered captive, not a king:
“Jesus can make a dying bed
Feel soft as downy pillows are;
Here on His breast I lean my head,
And breathe my life out sweetly there.”
IX.

We watch the dying man meanwhile,


His face all radiant with a smile;
His lips still move, as if in prayer,
A prayer we may not fully share;
But One is near, whose gracious ear,
The deep unuttered groan can hear.
Nor need we doubt or judge amiss,
What the heart’s inmost yearning is.
The quivering lip, the tearful eye,
Can well attest the earnest cry,
Of the stirred soul’s deep agony;
And taught of God, we join the prayer,
We may not fully hear or share.
Our eyes and hearts to Heaven we raise,
While thus the dying Indian prays:—
“God of eternal Love,
Look from Thy throne above,
Bow down thy gracious ear,
My dying prayer to hear;
Fulfil Thy promises,
Thy promises to bless
The widow and the fatherless.
Grant this last boon I crave!
May they have bread when I am dead,
And by thy bounty still be fed,
When I am in my grave.
Better than earthly father’s care,
Oh! may they in thy goodness share!
Grant them all needed good;
For soul and body, food;
And may thy mighty arm,
Protect them from all harm.
I leave them at thy call,
Mother and children all:
Oh! let no fears appal!
And let them never fail or fall!
I trust them, Lord, to Thee,
Thou wilt their Father be,
For time and for eternity.
Thy promises are sure,
The needy, helpless, poor,
Though crushed to death and dust,
May in Thy goodness trust,
And rest upon thy Word,
Thou ever blessed Lord!”
“Oh! bless my people! bless
Them in their helplessness!
Their poverty and wretchedness,
Their misery and distress.
Bless the whole Indian race!
That they may know thy grace!
Do thou their hearts prepare,
That they may freely share,
Those blessings rich and rare,
That from the Gospel flow,—
Salvation here below,
At all times trusting Thee, and go
To that bright World on high,
Of Glory when they die;
That they may shine,
In Love divine,
And with Thee rest
Forever blest!”
X.

Now droops his weary head


Exhausted on his bed.
His dying prayer has ceased;
Convulsive heaves his breast;
We deem him sunk to rest,
Breathing his last and best;
When suddenly his eyes
He opens on the skies,
And startling us with surprise,
He waves his hand and cries:
“I see, I see the place!
I see my Saviour’s face!
Look, children, look! your eyes
Raise, and look toward the skies!
Bright beams of Glory
Come hovering o’er me!
See! see! they’re opening wide,
The flaming gates of Paradise!
Bright angels downward glide,
And standing near my side,
They smile and bid me come,
To my eternal home.”
XI.

He dies, the happy Indian dies,


Closes his eyes to earth, and flies
Up to the regions of the skies.
Angelic legions lead the way,
To the portals of celestial day.
Wide spreads the news, all Heaven rings,
Angels and ransomed spirits wave their wings,
All lowly bending to the King of kings;
Mingling their loftiest harmonies,
Their sweetest, softest melodies,
High Heaven’s eternal Minstrelsies,
With harp and voice and choral symphonies,
Loud as the sounding of ten thousand seas!
They shout him welcome to his heavenly Home:
“John Paul has come! John Paul has come!”
Bear the glad tidings far
As the remotest star!
Let every tongue,
The shout prolong!
Sound the Redeemer’s praise,
In loudest, loftiest lays!
Your noblest anthems raise
To everlasting days,
To Him who bought him
With His precious blood,
To Him who brought him
To this bright Abode
Of perfect blessedness,
And Everlasting Peace,
“The Bosom of his Father and his God!”
XII.

Oh! Bliss Immortal! hail! all hail!


All glory, honour, to the Lamb who died!
Now seated glorious at His Father’s side.
Sound through the Universe his Name!
His matchless Love his Fame proclaim!
Till all His foes are put to shame.
And let the Story of the Cross prevail
O’er every Mountain, Island, Hill, and Dale,
Of the wide world, and satan’s power destroy,—
The wondrous news thrill every heart with joy—
Wafted on every breeze, by every swelling gale,
Till sin and suffering, shame and sorrow fail;
’Gainst Love Omnipotent no force prevail;
Till all His foes subdued shall bow the knee,
To Him who died on Calvary’s bloody tree,
For lost and guilty men, of every race,
Of every nation, station, time and place.
Oh swell the joyful notes of Jubilee!
The year of Grace! the year of Liberty!
Burst! burst! ye prison bars! let Man be free!
He died for all, of every tribe and hue,
Anglican, Indian, Ethiop, Greek and Jew.
All, all are welcome! wide heaven’s gates expand;
There every name is known from every Land,
There burst Hosannas, Heaven’s loud acclaim,
O’er every new-arrived, his name they name.
While all the blood-washed Throng,
In accents loud and long,
Their rapturous joy proclaim,
Shouting and singing, Glory to the Lamb!
All praise to Him who sits upon the Throne,
Who rules the Universe, the Lord alone!
Jehovah, Jesus, Saviour, Great I AM!
To Him who bought us
With His precious blood;
To Him who brought us
To this Bright Abode,
Of perfect Blessedness,
And Everlasting Peace,
“The Bosom of Our Father and our God!”

Latin Translations.

[The following attempts at a


translation of a couple of Psalms, and
some of our beautiful Evangelical
Hymns into Latin, will interest those
who are acquainted with that noble old
Tongue; more especially if they are at
all conversant with the Latin
Hymnology and methods of
versification of what are designated
the Middle Ages.]
Psalmus XXIII.

1. Est Jehova Pastor meus,


Meus Dominus et Deus,—
Ego impotens et reus—
Ergo non carebo.
Suam ovem stabulatque,
Prata graminosa datque.
Rivis placidis lavatque,
Illuc ducit, propinatque;
Itaque valebo.

2. Animamque reportavit
Meam, saepe recreavit;
Me quaesivit et servavit,
Optimus Curator.
Vüs rectis, praeparatis,
Aequitati consecratis,
Ducit Deus bonitatis,
Propter suum nomen gratis,
Ductor et Salvator.

3. Transeam caliginosa
Loca, et calamitosa,
Dura, dira, luctuosa,
Hostes et obstantes;
Non formido aerumnosa
Mala, tetra, dolorosa;
Gaudens fero lacrimosa,
Inter Te amantes.

You might also like