Full Download Expert Twisted: Event-Driven and Asynchronous Programming with Python 1st Edition Mark Williams PDF DOCX
Full Download Expert Twisted: Event-Driven and Asynchronous Programming with Python 1st Edition Mark Williams PDF DOCX
com
https://textbookfull.com/product/expert-twisted-event-
driven-and-asynchronous-programming-with-python-1st-edition-
mark-williams/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/expert-twisted-event-driven-and-
asynchronous-programming-with-python-1st-edition-mark-williams-2/
textboxfull.com
https://textbookfull.com/product/using-asyncio-in-python-
understanding-python-s-asynchronous-programming-features-caleb-
hattingh/
textboxfull.com
https://textbookfull.com/product/practical-microservices-build-event-
driven-architectures-with-event-sourcing-and-cqrs-1st-edition-ethan-
garofolo/
textboxfull.com
Combine Asynchronous Programming with Swift First Edition
Scott Gardner
https://textbookfull.com/product/combine-asynchronous-programming-
with-swift-first-edition-scott-gardner/
textboxfull.com
https://textbookfull.com/product/combine-asynchronous-programming-
with-swift-first-edition-scott-gardner-2/
textboxfull.com
https://textbookfull.com/product/asynchronous-android-programming-
helder-vasconcelos/
textboxfull.com
https://textbookfull.com/product/reactive-programming-with-
rxjs-5-untangle-your-asynchronous-javascript-code-1st-edition-sergi-
mansilla/
textboxfull.com
Expert Twisted
Event-Driven and Asynchronous
Programming with Python
—
Mark Williams
Cory Benfield
Brian Warner
Moshe Zadka
Dustin Mitchell
Kevin Samuel
Pierre Tardy
Expert Twisted
Event-Driven and Asynchronous
Programming with Python
Mark Williams
Cory Benfield
Brian Warner
Moshe Zadka
Dustin Mitchell
Kevin Samuel
Pierre Tardy
Expert Twisted
Mark Williams Cory Benfield
Pasadena, CA, USA London, UK
Pierre Tardy
Toulouse, France
Introduction������������������������������������������������������������������������������������������������������������xix
Part 1: Foundations���������������������������������������������������������������������������������������� 1
Chapter 1: An Introduction to Event-Driven Programming with Twisted����������������� 3
A Note About Python Versions������������������������������������������������������������������������������������������������������� 4
What Is Event-Driven Programming?�������������������������������������������������������������������������������������������� 4
Multiple Events����������������������������������������������������������������������������������������������������������������������������� 5
Application(tkinter.Tk()).mainloop()����������������������������������������������������������������������������������������������� 6
Multiplexing and Demultiplexing��������������������������������������������������������������������������������������������������� 7
The select Multiplexer������������������������������������������������������������������������������������������������������������������� 9
Its History, Its Siblings, and Its Purpose���������������������������������������������������������������������������������� 9
select and Sockets������������������������������������������������������������������������������������������������������������������ 9
The How and Why of Socket Events�������������������������������������������������������������������������������������� 11
Handling Events��������������������������������������������������������������������������������������������������������������������� 12
An Event Loop with select����������������������������������������������������������������������������������������������������� 13
Event-Driven Clients and Servers������������������������������������������������������������������������������������������ 15
Non-blocking I/O������������������������������������������������������������������������������������������������������������������������� 18
Knowing When to Stop���������������������������������������������������������������������������������������������������������� 18
Tracking State������������������������������������������������������������������������������������������������������������������������ 19
State Makes Programs Complex������������������������������������������������������������������������������������������� 23
Managing Complexity with Transports and Protocols����������������������������������������������������������������� 23
Reactors: Working with Transports���������������������������������������������������������������������������������������� 24
v
Table of Contents
vi
Table of Contents
Coroutines in Python������������������������������������������������������������������������������������������������������������������� 88
Coroutines with yield from���������������������������������������������������������������������������������������������������� 88
Coroutines async and await�������������������������������������������������������������������������������������������������� 90
Awaiting Deferreds��������������������������������������������������������������������������������������������������������������������� 95
Coroutines to Deferreds with ensureDeferred���������������������������������������������������������������������������� 97
Multiplexing Deferreds���������������������������������������������������������������������������������������������������������������� 99
Testing Deferreds���������������������������������������������������������������������������������������������������������������������� 102
Summary���������������������������������������������������������������������������������������������������������������������������������� 106
vii
Table of Contents
Client����������������������������������������������������������������������������������������������������������������������������������� 159
Registry������������������������������������������������������������������������������������������������������������������������������� 160
Build������������������������������������������������������������������������������������������������������������������������������������ 160
Multi-stage Build����������������������������������������������������������������������������������������������������������������� 161
Python on Docker���������������������������������������������������������������������������������������������������������������������� 163
Deployment Options������������������������������������������������������������������������������������������������������������ 163
Full env�������������������������������������������������������������������������������������������������������������������������������� 163
Virtualenv���������������������������������������������������������������������������������������������������������������������������� 169
Pex��������������������������������������������������������������������������������������������������������������������������������������� 170
Build Options����������������������������������������������������������������������������������������������������������������������� 172
One Big Bag������������������������������������������������������������������������������������������������������������������������� 172
Copying Wheels Between Stages���������������������������������������������������������������������������������������� 172
Copying Environment Between Stages������������������������������������������������������������������������������� 173
Copying the Pex Executable Between Stages��������������������������������������������������������������������� 173
Automation with Dockerpy�������������������������������������������������������������������������������������������������� 173
Twisted on Docker�������������������������������������������������������������������������������������������������������������������� 174
ENTRYPOINT and PID 1�������������������������������������������������������������������������������������������������������� 174
Custom Plugins�������������������������������������������������������������������������������������������������������������������� 174
NColony������������������������������������������������������������������������������������������������������������������������������� 175
Summary���������������������������������������������������������������������������������������������������������������������������������� 178
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 373
xii
About the Authors
Mark Williams works on Twisted. At eBay and PayPal, he worked on high-performance
Python web services (over a billion requests a day!), application and information
security, and porting enterprise, Java-only libraries to Python.
Cory Benfield is an open source Python developer heavily involved in the Python HTTP
community. He's a Requests core contributor, a urllib3 core contributor, and the lead
maintainer of the Hyper Project, a collection of HTTP and HTTP/2 tools for Python. For
his sins, he also helps out with the Python Cryptographic Authority on PyOpenSSL.
Brian Warner is a security engineer and software developer, having worked at Mozilla
on Firefox Sync, the Add-On SDK, and Persona. He is co-founder of the Tahoe-LAFS
distributed secure filesystem, and develops secure storage and communication tools.
Moshe Zadka has been part of the open source community since 1995, made his first
core Python contributions in 1998, and is a founding member of the Twisted open
source project. He also loves to teach Twisted and Python, having given tutorials at
several conferences as well as regularly blogging.
Dustin Mitchell has contributed to Buildbot and is a member of the TaskCluster team
at Mozilla, having also worked on the Release Engineering, Release Operations, and
Infrastructure teams.
Kevin Samuel has been a Dev and trainer since Python 2.4 and has been putting
his skills to work in East Europe, North America, Asia, and West Africa. He has been
working closely with the Crossbar.io team and is an active member of the French Python
community.
Pierre Tardy is a continuous integration specialist with Renault Software Labs, and he is
currently the lead committer for Buildbot.
xiii
About the Technical Reviewers
Julian Berman is a New York-based software developer and
open source contributor. He is the author of the jsonschema
Python library, an occasional contributor to the Twisted
ecosystem, and an active member of the Python community.
Shawn Shojaie lives in the clement chaparral of California's Bay Area, where he works
as a back-end software engineer. He has worked at Intel, NetApp, and now SimpleLegal,
where he happily builds web-based applications for legal services. He spends weekdays
writing Django and tuning PostgreSQL, and his weekends contributing to open source
projects like django-pylint, occasionally editing technical essays. Find out more at him at
shawnshojaie.com.
Tom Most is a software engineer in the telecommunications industry. He is a Twisted
committer with 10 years of experience of applying Twisted to web services, client
libraries, and command-line applications. He is the maintainer of Afkak, the Twisted
Kafka client. He can be found online at freecog.net and reached at [email protected].
xv
Acknowledgments
Thanks to my wife, Jennifer Zadka, without whose support I could not have done it.
Thanks to my parents, Yaacov and Pnina Zadka, who taught me how to learn.
Thanks to Glyph Lefkowitz, for teaching me things about Python, about programming,
and about being a good person.
—Moshe Zadka
Thanks to Mahmoud Hashemi and David Karapetyan for their feedback. Thanks to
Annie for putting up with me while I wrote
—Mark Williams
xvii
Introduction
Twisted has recently celebrated its sweet sixteen birthday. It has been around for a
while; and in that time, it grew to be a powerful library. In that time, some interesting
applications have been built on top of it. In that time, many of us learned a lot about how
to use Twisted well, how to think about networking code, and how to architect event-
based programs.
After going through the introductory materials that we have on the Twisted site,
a common thing to hear is “What now? How can I learn more about Twisted?” The
usual way we answered that question is with a question: “What do you want to do with
Twisted?” This book shows how to do interesting things with Twisted.
Each of the contributors to this book has done slightly different things with Twisted
and learned different lessons. We are excited to present all of these lessons, with the
goals of making them common knowledge in the community.
Enjoy!
xix
PART 1
Foundations
CHAPTER 1
An Introduction to
Event-Driven
Programming with Twisted
Twisted is a powerful, well-tested, and mature concurrent networking library and
framework. As we’ll see in this book, many projects and individuals have used it to great
effect for more than a decade.
At the same time, Twisted is large, complicated, and old. Its lexicon teems with
strange names, like “reactor,” “protocol,” “endpoint,” and “Deferred.” These describe a
philosophy and architecture that have baffled both newcomers and old hands with years
of Python experience.
Two fundamental programming paradigms inform Twisted’s pantheon of APIs:
event-driven programming and asynchronous programming. The rise of JavaScript
and the introduction of asyncio into the Python standard library have brought both
further into the mainstream, but neither paradigm dominates Python programming
so completely that merely knowing the language makes them familiar. They remain
specialized topics reserved for intermediate or advanced programmers.
This chapter and the next introduce the motivations behind event-driven and
asynchronous programming, and then show how Twisted employs these paradigms.
They lay the foundation for later chapters that explore real-world Twisted programs.
We’ll begin by exploring the nature of event-driven programming outside of the
context of Twisted. Once we have a sense of what defines event-driven programming,
we’ll see how Twisted provides software abstractions that help developers write clear
and effective event-driven programs. We’ll also stop along the way to learn about
some of the unique parts of those abstractions, like interfaces, and explore how they’re
documented on Twisted’s website.
3
© Mark Williams, Cory Benfield, Brian Warner, Moshe Zadka, Dustin Mitchell, Kevin Samuel, Pierre Tardy 2019
M. Williams et al., Expert Twisted, https://doi.org/10.1007/978-1-4842-3742-7_1
Chapter 1 An Introduction to Event-Driven Programming with Twisted
By the end of this chapter you’ll know Twisted terminology: protocols, transports,
reactors, consumers, and producers. These concepts form the foundation of Twisted’s
approach to event-driven programming, and knowing them is essential to writing useful
software with Twisted.
import sys
line = sys.stdin.readline().strip()
if line == "h":
print("Hello")
else:
print("World")
The availability of a line of input over standard input is an event. Our program
pauses on sys.stdin.readline(), which asks the operating system to allow the user to
input a complete line. Until one is received, our program can make no progress. When
the operating system receives input, and Python’s internals determine it’s a line, sys.
stdin.readline() resumes our program by returning that data to it. This resumption
is the event that drives our program forward. Even this simple program, then, can be
understood as an event-driven one.
4
Chapter 1 An Introduction to Event-Driven Programming with Twisted
Multiple Events
A program that receives a single event and then exits doesn’t benefit from an event-
driven approach. Programs in which more than one thing can happen at a time,
however, are more naturally organized around events. A graphical user interface implies
just such a program: at any moment, a user might click a button, select an item from a
menu, scroll through a text widget, and so on.
Here’s a version of our previous program with a Tkinter GUI:
class Application(tkinter.Frame):
def __init__ (self, root):
super(Application,self). __init__ (root)
self.pack()
self.helloButton = tkinter.Button(self,
text="Say Hello",
command=self.sayHello)
self.worldButton = tkinter.Button(self,
text="Say World",
command=self.sayWorld)
self.output = scrolledtext.ScrolledText(master=self)
self.helloButton.pack(side="top")
self.worldButton.pack(side="top")
self.output.pack(side="top")
def outputLine(self, text):
self.output.insert(tkinter.INSERT, text+ '\n')
def sayHello(self):
self.outputLine("Hello")
def sayWorld(self):
self.outputLine("World")
5
Chapter 1 An Introduction to Event-Driven Programming with Twisted
Application(tkinter.Tk()).mainloop()
This version of our program presents the user with two buttons, either of which can
generate an independent click event. This differs from our previous program, where only
sys.stdin.readline could generate the single “line ready” event.
We cope with the possible occurrence of either button’s event by associating event
handlers with each one. Tkinter buttons accept a callable command to invoke when they
are clicked. When the button labeled “Say Hello” generates a click event, that event
drives our program to call Application.sayHello as shown in Figure 1-1. This, in turn,
outputs a line consisting of Hello to a scrollable text widget. The same process applies to
the button labeled “Say Hello” and Application.sayWorld.
Figure 1-1. Our Tkinter GUI application after a series of clicks of “Say Hello” and
“Say World”
6
Chapter 1 An Introduction to Event-Driven Programming with Twisted
3. An event loop waits for events and invokes the event handler
associated with each. Not all event-driven programs have an event
loop; our sys.stdin.readline example did not because it only
responds to a single event. However, most resemble our tkinter
example in that they process many events before finally exiting.
These kinds of programs use an event loop.
def mainloop(self):
while self.running:
ready = [button for button in self.buttons if button.hasEvent()]
if ready:
self.dispatchButtonEventHandlers(ready)
mainloop continually polls each button for a new event, dispatching event handlers
only for those that have an event ready. When no events are ready, the program makes
no progress because no action has been taken that requires a response. An event-driven
program must suspend its execution during these periods of inactivity.
7
Chapter 1 An Introduction to Event-Driven Programming with Twisted
The while loop in our mainloop example suspends its program until one of the
buttons has been clicked and sayHello or sayWorld should run. Unless the user is
supernaturally fast with a mouse, this loop spends most of its time checking buttons that
haven’t been clicked. This is known as a busy wait because the program is actively busy
waiting.
A busy wait like this pauses a program’s overall execution until one of its event
sources reports an event, and so it suffices as a mechanism to pause an event loop.
The inner list comprehension that powers our implementation’s busy wait asks
a critical question: Has anything happened? The answer comes from the ready
variable, which contains all buttons that have been clicked in a single place. The
truthiness of ready decides the answer to the event loop’s question: when ready is
empty and thus falsey, no buttons have been clicked and so nothing has happened.
When it’s truthy, however, at least one has been clicked, and so something has
happened.
The list comprehension that constructs ready coalesces many separate inputs
into one. This is known as multiplexing, while the inverse process of separating
different inputs out from a single coalesced input is known as demultiplexing.
The list comprehension multiplexes our buttons into ready while the
dispatchButtonEventHandlers method demultiplexes them out by invoking each
event’s handler.
We can now refine our understanding of event loops by precisely describing how
they wait for events:
8
Chapter 1 An Introduction to Event-Driven Programming with Twisted
While Twisted can integrate with graphical user interfaces, and in fact has special
support for tkinter, it is at its heart a networking engine. Sockets, not buttons, are the
fundamental object in networking, and operating systems expose efficient primitives for
multiplexing socket events. Twisted’s event loop uses these primitives to wait for events.
To understand Twisted’s approach to event-driven programming, we must understand
the interaction between these sockets and these multiplexing networking primitives.
9
Chapter 1 An Introduction to Event-Driven Programming with Twisted
A full explanation of the socket API is beyond the scope of this book. Indeed, we
expect that the parts we discuss will lead you to prefer Twisted! The preceding code,
however, contains more fundamental concepts than irrelevant details:
client and server are two ends of the same TCP connection. An established TCP
connection has no concept of “client” and “server”; our client socket has the same
privileges to read, write, or close the connection as our server:
11
Chapter 1 An Introduction to Event-Driven Programming with Twisted
We can ask select about the events our sockets have just generated:
We instruct select not to wait for any new events by providing a timeout of 0. As
explained above, our client and server sockets might be readable or writable, while
our listener, which can only accept incoming connections, can only be readable.
If we had omitted the timeout, select would pause our program until one of the
sockets it monitored became readable or writable. This suspension of execution is
analogous to the multiplexing busy-wait that polled all buttons in our naive mainloop
implementation above.
Invoking select multiplexes sockets more efficiently than a busy wait because
the operating system will only resume our program when at least one event has been
generated; inside the kernel an event loop, not unlike our select, waits for events from
the network hardware and dispatches them to our application.
Handling Events
select returns a tuple with three lists, in the same order as its arguments. Iterating
over each returned list demultiplexes select’s return value. None of our sockets have
generated readable events, even though we’ve written data to both client and server;
our preceding calls to recv emptied their read buffers, and no new connections have
arrived for listener since we accepted server. Both client and server have generated
a writable event, however, because there’s space available in their send buffers.
Sending data from client to server causes server to generate a readable event, so
select places it in the readables list:
>>> client.sendall(b'xyz')
>>> readable, writable, _ = select.select(maybeReadable, maybeWritable, [], 0)
>>> readable == [server]
True
12
Chapter 1 An Introduction to Event-Driven Programming with Twisted
The writable list, interestingly, once again contains our client and server sockets:
If we called select again, our server socket would again be in readable and our
client and server sockets again in writable. The reason is simple: as long as data
remains in a socket’s read buffer, it will continuously generate a readable event, and as
long as space remains in a socket’s write buffer, it will generate a writable event. We can
confirm this by recving the data client sent to server and calling select again for new
events:
Emptying server’s read buffer has caused it to stop generating readable events, and
client and server continue to generate writable events because there’s still space in
their write buffers.
13
Chapter 1 An Introduction to Event-Driven Programming with Twisted
import select
class Reactor(object):
def __init__ (self):
self._readers = {}
self._writers = {}
def addReader(self, readable, handler):
self._readers[readable] = handler
def addWriter(self, writable, handler):
self._writers[writable] = handler
def removeReader(self, readable):
self._readers.pop(readable,None)
def removeWriter(self, writable):
self._writers.pop(writable,None)
def run(self):
while self._readers or self._writers:
r, w, _ = select.select(list(self._readers), list
(self._writers), [])
for readable in r:
self._readers[readable](self, readable)
for writable in w:
if writable in self._writers:
self._writers[writable](self, writable)
We call our event loop a reactor because it reacts to socket events. We can request
our Reactor call readable event handlers on sockets with addReader and writable event
handlers with addWriter. Event handlers accept two arguments: the reactor itself and
the socket that generated the event.
The loop inside the run method multiplexes our sockets with select, then
demultiplexes the result between sockets that have generated a read event and sockets
that have generated a write event. The event handlers for each readable socket run
first. Then, the event loop checks that each writable socket is still registered as a writer
14
Exploring the Variety of Random
Documents with Different Content
I don’t mean those that are insincere or hypocritical: but all those
who are content with outward religion, with any thing short of that
inward holiness, that newness of spirit which the gospel describes.
A Christian is sober, not only so far as suits with a regular life, but
so as becomes one who is born of the Holy Spirit, who dwelleth in
God and God in him.
For indeed, neither charity, nor temperance, nor justice, nor any
other virtues (as they are called) are parts of Christian holiness, till
they spring from holiness of heart, from the mind that was in Christ.
Some people who begin to look toward religion, think they have
done enough, when they have reformed the outward course of their
lives; when they have left off their gross vices and follies, or are
grown careful of some particular duties.
Thus a man who has been a drunkard many years, thinks he has
made a sufficient change by becoming temperate: another imagines,
he is in a very good and safe state, because he does not neglect the
public worship, as he used to do: a lady fancies she lives enough to
God because she has left off plays, and lives more at home than
formerly.
But let such people remember, that they who thus measure
themselves by themselves are not wise. Let them remember that
they are not disciples of Christ, till they have, like him, offered their
whole soul and body as a reasonable living sacrifice to God; that
they are not members of Christ’s mystical body, till they are united
unto him by a new spirit; that they have not entered into the kingdom
of God, till they have entered into an infant simplicity of heart, till they
are so born of God as not to commit sin, so full of an heavenly Spirit
as to have overcome the world.
*If religion has raised us into a new world; if it has filled us with
new ends of life; if it has taken possession of our hearts, altered the
whole turn of our minds, and changed the whole stream of our
affections: if it has given us new joys and griefs, new hopes and
fears; if all things in us are become new: if the love of God is shed
abroad in our hearts, by the Holy Ghost given unto us, and this Spirit
beareth witness with our spirit that we are the children of God: then
are we Christians, not in name only, but in truth; then we do believe
in the Holy Jesus, and we shall rejoice in the day of Christ, that we
have not run in vain, neither laboured in vain.
CHAP. II.
C
HRISTIANITY requires a renouncing of the world, and all
worldly tempers.
It ranks the world, with the flesh and the devil, as an equal enemy
to those glorious ends which it proposes.
II. For not only the vices, the wickedness, and vanity of this world,
but even its most lawful concerns, if unduly pursued, make men
unable to enter into the true state of Christianity.
But they don’t consider that their own employments also are as
vain as vanity itself: they don’t consider that any business or
employment, if it has got hold of the heart, renders men as vain and
odious in the sight of God, as any sensual gratification.
IV. *The wisdom of this world indeed gives an importance and air
of greatness to several ways of life, and ridicules others as vain and
contemptible, which differ only in their kind of vanity. But the wisdom
from above condemns all labour as equally fruitless, which hinders
our labouring after everlasting life. For what can it signify whether a
man forgets God in his farm, or in a shop, or at a gaming table? The
world is full as important in its pleasures as in its cares; there is no
more wisdom in the one than in the other. And the man who, by the
cares and business of the world is made less affected to the things
of God, is no wiser than he who takes his delight in running foxes
and hares out of breath.
For there is no wisdom in any thing but religion. Nor is any way of
life less vain than another, but as it is made serviceable to piety, and
conspires with the designs of religion, to raise mankind to a
participation and enjoyment of the divine nature.
Men of sober business, who seem to act the grave part of life,
generally condemn these ways of life.
But why are they to be condemned? Produce but the true reason
why any of these are vain and sinful, and the same reason will
conclude against every way of life which is not wholly devoted to
God.
VI. Let the man who is deep in worldly business, but shew the
vanity and shame of a life devoted to pleasures, and the same
reasons will shew the vanity and shame of a life filled with worldly
cares. So that whosoever can condemn sensuality, ambition, or any
way of life upon the principles of reason and religion, carries his own
condemnation within his own breast, unless his life be entirely
devoted to God.
*In like manner our care after some worldly things is necessary.
But if this care is not bounded by the just wants of nature, if it
wanders into unnecessary pursuits, and fills the mind with false
desires and cravings; if it wants to add an imaginary splendour to the
plain demands of nature, it is vain and irregular; it is the care of an
epicure, a longing for sauces and ragous, and corrupts the soul like
any other sensual indulgence.
For this reason our Lord points so many of his doctrines at the
common allowed employments of life, to teach us, that they may
employ our minds as falsely and dangerously as any trifles whatever.
IX. It must not be said that these doctrines are not plainly enough
taught in scripture, because the lives and behaviour of Christians are
so contrary to them. For if the lives of Christians might be alledged
against the doctrines of scripture, none of them would have lasted to
this day.
It is one of the ten commandments, Thou shalt not take the name
of the Lord thy God in vain. And our Saviour has forbid swearing,
yea, in the most solemn manner. Yet where more swearing than
among Christians, and among such Christians as would think it hard
to be reckoned a reproach to the Christian name?
The scripture says of Christians, that they are born of God, and
have overcome the world. Can they then be reckoned of that
number, who have not so much as overcome that flagrant sin, to
which they have no temptation in nature?
Well therefore may the doctrines of heavenly-mindedness, and
contempt of the world be disregarded, since they run counter to all
the corruptions of flesh and blood, to all the pride and vanity of our
nature.
X. But let those who are startled at these doctrines, deal faithfully
with their own hearts, and ask themselves whether they should not
have had the same dislike to them, had they lived in our Saviour’s
days? Or whether they can find any one reason, why they should
have been so spiritual and heavenly then, which is not as good and
as strong a reason for their being as spiritual and heavenly now?
Yet, if an apostle was to raise from the dead, calling rich and
great men to these doctrines, they would drive their coaches from
such a preacher, rather than be saved at such a price.
XI. To set this great truth in a still clearer light, I will appeal a little
even to the imagination of the reader.
Let it be supposed, that rich men are now enjoying their riches,
and taking all the usual delights of plenty; that they are labouring for
the meat that perisheth, contriving scenes of pleasure, and spending
their estates in proud expences.
XII. *To proceed; Let us suppose that a rich man was to put up
such a prayer as this to God:
I beg of such that they would heartily condemn the profane and
unchristian spirit of the foregoing prayer, and that they would satisfy
themselves, nothing can be more odious and contrary to religion.
But let them be assured also of this, that the same things which
make an unchristian prayer, make an unchristian life.
From all this it is plain, that the present followers of Jesus Christ,
have no more to do with worldly enjoyments, than those he chose
while he himself was on earth; and that we are to have the same
heavenly devotion to God, the same affection, as any of those he
conversed with in the days of his flesh.
I don’t question but the rich young man in the gospel could have
made a very good apology for himself, and have shewn how
reasonable and innocent a thing it was, for so good and so young a
man to enjoy an estate.
The rich man in torments could have alledged how much good he
did with his fortune; how many trades he encouraged with his purple
and fine linen, and faring sumptuously every day; and how he
conformed to the ends of society, by so spending his estate.
XVII. *But still the word of God shall not pass away. Having food
and raiment, let us be therewith content. For they who will be rich fall
into a temptation and a snare, and into many foolish and hurtful
lusts, which drown men in destruction and perdition. 1 Tim. vi. 8.
The rich man in the gospel was a ruler, a young man, and a good
man: if therefore there are any of his rank who are neither young nor
good, it can hardly be thought, they have less to do to inherit eternal
life.
And as for those who, like him, have kept the commandments of
God from their youth, I dare not tell them, that they are not under a
necessity of offering all their wealth to God, and of making their
estates, however acquired, not the support of vain indulgences, but
the relief of their brethren.
And yet he that had done nothing but sleep and dream to the
time of his death, might as well say, that he had been working out his
salvation with fear and trembling, as he that has been living in luxury,
splendour, and sensual gratifications.
The distinctions of civil life have their use; but if any one thinks he
may be less devoted to God, less afraid of the corruptions of
pleasure and pride, because he is born of a rich family, he is as
much mistaken as he that fancies he has a privilege to steal,
because he was born of a Father that was poor.
XX. If the rich or great man can find out a course of pleasures,
that support no wrong turn of mind, an indulgence which does not
gratify sensuality, entertainments which feed no vain passions: if
they can find out such instances of splendour and greatness, as
shew they love God with all their hearts, and as gratify neither the
lust of the flesh, the lust of the eye, nor the pride of life, religion has
no command against such enjoyments.
But if this cannot be done, then the rich have no more permission
to live in vain indulgences than the poor have to steal.
If therefore they that live in pomp and shew, live therein out of
choice, and are not willing to live otherwise, we must talk nonsense if
we do not say their minds are as vain as the vanity of their state.
Christians are to love God with all their heart, with all their soul,
with all their mind, and with all their strength.
A man that has his head and his heart full of worldly concerns,
can no more love God with all his strength, than a man, who has his
eyes on the ground, can be looking towards heaven with all the
strength of his sight.
XXIII. It is certain, that we unavoidably love every thing in
proportion as it appears to be our happiness: if it appears to be half
our happiness, it will necessarily have half the strength of our love:
and if it appears to be all our happiness, we shall love it with all our
strength.
And indeed what can be more ridiculous than to fancy, that a man
who is taken up with the enjoyments of the world, is at the same time
loving God with all his soul and with all his strength?
This will also teach him, that the true love of his neighbour is as
inconsistent with the love of the world, as duelling is inconsistent with
meekness and the forgiveness of injuries.
XXV. *This love is a temper that suits only such beings as have
one common undivided happiness, wherein they cannot be rivals to
one another. Now this is the state of all Christians, who have as truly
one common happiness as they have one common God. But if we
put ourselves out of this state, and seek for happiness in the
enjoyments of this life, we are as incapable of this love, as wolves
and bears that live upon prey.
Perhaps they have not those bitter envyings and hatreds to which
ambitious worldlings are subject. But still they have as certainly, in
their degree, and in proportion to their love of the world, their
envyings and hatreds, and want of sincere love, as other men.
XXVII. For a further proof of this, we need only look into the
world, and see the spirit that appears among almost all Christians.
And this necessarily springs from hence, that all Christians are
busy in attending to their worldly interests, intending only to keep
clear of dishonest practices: that is, they use the world as far as
honest Heathens or Jews would do, and consequently have such
tempers as Jews and Heathens have.
For it is not only cheating and dishonesty, but the bare desire of
worldly things, and the placing happiness in them, that lays the
foundation of all these unchristian tempers; and divides Christians
into more parties than there are families among them.
The first step our desires take beyond things of necessity, ranks
us among worldlings, and raises in our minds all those tempers,
which disturb the minds of worldly men.
XXIX. You think yourself conformable to Christianity, because you
are moderate in your desires. You don’t desire a large estate; you
desire only a little finery, a little state, and to have things genteel
about you.
Imagine now, that what you say, of moderate desires, and little
fineries, had been said to our blessed Saviour when he was upon
earth, calling men to renounce the world and deny themselves.
Now the spirit of Christianity is the same spirit that was in Christ
when he was upon earth. And if we have reason to think that such a
pretence would have been severely condemned by Christ, we have
the same reason to be sure, it is as severely condemned by
Christianity.
XXX. Had our blessed Saviour a little before he left the world,
given estates to his apostles, with a permission for them to enjoy
little fineries, and a moderate state in a genteel manner, he had
undone all that he had said of the contempt of the world, and
heavenly-mindedness. Such a permission had been a contradiction
to the main doctrines which he had taught.
And how blind and weak must we be, if we can think that we may
live in a spirit and temper, which could not possibly be the spirit and
temper of Christ and his apostles?
XXXI. *Another pretence for worldly care and labour after riches,
is to provide for our families.
You want to leave fortunes to your children, that they may have
their share in the figure and shew of the world. Now consider, do you
do this on principles of religion, as the best thing you can do, either
for yourself or them?
Can you then be said, to have chosen the one thing needful for
yourself, or the one thing needful for them, who take such care to put
them in a state of life, that is a snare and a temptation, and the most
likely of all others, to fill their minds with foolish and hurtful lusts?
Is it your kindness toward them that puts you upon this labour?
Consider therefore what this kindness is founded upon? Perhaps it is
such a kindness as when tender mothers carry their daughters to
plays and balls: such a kindness as when indulgent fathers support
their sons in all the expence of their follies. Such kind parents may
more properly be called the betrayers and murderers of their
children.
You love your children, and therefore you would have them rich. It
is said of our blessed Saviour, that he loved the young rich man that
came unto him, and therefore he bid him sell all that he had. What a
contrariety is here? The love which dwelleth in you, is as contrary to
the love which dwelt in Christ as darkness is to light.
If you would die like a Christian, must you not endeavour to fill
their minds with your dying thoughts? Must you not tell them that
very soon the world will signify no more to them than it does to you?
And that there is a vanity, a littleness in the things of this life, which
only dying men feel as they ought?
Will you not tell them, that all your own failings, the irregularity of
your life, the folly of your tempers, and your failure of Christian
perfection, has been owing to wrong opinions of the value of worldly
things? And that if you had always seen the world in the same light
that you see it now, your life had been devoted to God, and you
would have lived in all those holy tempers and heavenly affections in
which you now desire to die?
Will you not tell them, that riches spent upon ourselves, either in
the pleasures of ease and indulgence, in the vanity of dress, or in
state and grandeur, are the bane and destruction of our souls,
making us blindly content with dreams of happiness, till death
awakes us into real misery?
From all this therefore it appears, that your kindness for your
children is so far from being a good reason why you should so
carefully labour to leave them rich, and in the enjoyment of the state
and shew of the world; that if you die in a spirit of piety, if you love
them as Christ loved his disciples, your kindness will oblige you to
exhort them to renounce all such enjoyment of riches, as is contrary
to those holy tempers and that heavenly affection which you now find
to be the only good and happiness of human nature.
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.
textbookfull.com