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

PDF Advanced Guide To Python 3 Programming Hunt Download

ebook

Uploaded by

vanhiebeshoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

PDF Advanced Guide To Python 3 Programming Hunt Download

ebook

Uploaded by

vanhiebeshoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Full download test bank at ebook textbookfull.

com

Advanced Guide to Python 3

CLICK LINK TO DOWLOAD

https://textbookfull.com/product/advanced-
guide-to-python-3-programming-hunt/

textbookfull
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Python Advanced Programming: The guide to learn pyhton


programming Marcus Richards

https://textbookfull.com/product/python-advanced-programming-the-
guide-to-learn-pyhton-programming-marcus-richards/

Learn to Program with Python 3: A Step-by-Step Guide to


Programming Irv Kalb

https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-irv-kalb/

Learn to Program with Python 3: A Step-by-Step Guide to


Programming, 2nd Edition Irv Kalb

https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-2nd-edition-irv-
kalb/

A Beginner’s Guide to Scala, Object Orientation and


Functional Programming John Hunt

https://textbookfull.com/product/a-beginners-guide-to-scala-
object-orientation-and-functional-programming-john-hunt/
A Beginner's Guide to Scala, Object Orientation and
Functional Programming (Second Edition) John Hunt

https://textbookfull.com/product/a-beginners-guide-to-scala-
object-orientation-and-functional-programming-second-edition-
john-hunt/

Practical Programming An Introduction to Computer


Science Using Python 3 6 3rd Edition Paul Gries

https://textbookfull.com/product/practical-programming-an-
introduction-to-computer-science-using-python-3-6-3rd-edition-
paul-gries/

Python 3 Object Oriented Programming 3rd Edition Dusty


Phillips [Dusty Phillips]

https://textbookfull.com/product/python-3-object-oriented-
programming-3rd-edition-dusty-phillips-dusty-phillips/

Python Basics A Practical Introduction to Python 3


Fletcher Heisler

https://textbookfull.com/product/python-basics-a-practical-
introduction-to-python-3-fletcher-heisler/

Learn Python Programming A beginner s guide to learning


the fundamentals of Python language to write efficient
high quality code Romano

https://textbookfull.com/product/learn-python-programming-a-
beginner-s-guide-to-learning-the-fundamentals-of-python-language-
to-write-efficient-high-quality-code-romano/
Undergraduate Topics in Computer Science

John Hunt

Advanced Guide
to Python 3
Programming
Undergraduate Topics in Computer Science

Series Editor
Ian Mackie, University of Sussex, Brighton, UK

Advisory Editors
Samson Abramsky, Department of Computer Science, University of Oxford,
Oxford, UK
Chris Hankin, Department of Computing, Imperial College London, London, UK
Dexter C. Kozen, Department of Computer Science, Cornell University, Ithaca, NY,
USA
Andrew Pitts, University of Cambridge, Cambridge, UK
Hanne Riis Nielson , Department of Applied Mathematics and Computer Science,
Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Department of Computer Science, Stony Brook University,
Stony Brook, NY, USA
Iain Stewart, Department of Computer Science, Science Labs, University of
Durham, Durham, UK
Mike Hinchey, University of Limerick, Limerick, Ireland
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality
instructional content for undergraduates studying in all areas of computing and
information science. From core foundational and theoretical material to final-year
topics and applications, UTiCS books take a fresh, concise, and modern approach
and are ideal for self-study or for a one- or two-semester course. The texts are all
authored by established experts in their fields, reviewed by an international advisory
board, and contain numerous examples and problems, many of which include fully
worked solutions.
The UTiCS concept relies on high-quality, concise books in softback format, and
generally a maximum of 275–300 pages. For undergraduate textbooks that are
likely to be longer, more expository, Springer continues to offer the highly regarded
Texts in Computer Science series, to which we refer potential authors.

More information about this series at http://www.springer.com/series/7592


John Hunt

Advanced Guide to Python 3


Programming

123
John Hunt
Marshfield
Midmarsh Technology Ltd.
Chippenham, Wiltshire, UK

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-030-25942-6 ISBN 978-3-030-25943-3 (eBook)
https://doi.org/10.1007/978-3-030-25943-3
© Springer Nature Switzerland AG 2019
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part
of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission
or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this
publication does not imply, even in the absence of a specific statement, that such names are exempt from
the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publisher nor the
authors or the editors give a warranty, expressed or implied, with respect to the material contained
herein or for any errors or omissions that may have been made. The publisher remains neutral with regard
to jurisdictional claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
For Denise, my wife.
Preface

Some of the key aspects of this book are:


1. It assumes knowledge of Python 3 and of concepts such as functions, classes,
protocols, Abstract Base Classes, decorators, iterables, collection types (such as
List and Tuple) etc.
2. However, the book assumes very little knowledge or experience of the topics
presented.
3. The book is divided into eight topic areas; Computer graphics, Games, Testing,
File Input/Output, Database Access, Logging, Concurrency and Parallelism and
Network Programming.
4. Each topic in the book has an introductory chapter followed by chapters that
delve into that topic.
5. The book includes exercises at the end of most chapters.
6. All code examples (and exercise solutions) are provided on line in a GitHub
repository.

Chapter Organisation

Each chapter has a brief introduction, the main body of the chapter, followed by a
list of online references that can be used for further reading.
Following this there is typically an Exercises section that lists one or more
exercises that build on the skills you will have learnt in that chapter.
Sample solutions to the exercises are available in a GitHub repository that
supports this book.

vii
viii Preface

What You Need

You can of course just read this book; however following the examples in this book
will ensure that you get as much as possible out of the content.
For this you will need a computer.
Python is a cross platform programming language and as such you can use Python
on a Windows PC, a Linux Box or an Apple Mac etc. This means that you are not tied
to a particular type of operating system; you can use whatever you have available.
However you will need to install some software on your computer. At a mini-
mum you will need Python. The focus of this book is Python 3 so that is the version
that is assumed for all examples and exercises. As Python is available for a wide
range of platforms from Windows, to Mac OS and Linux; you will need to ensure
that you download the version for your operating system.
Python can be downloaded from the main Python web site which can be found at
http://www.python.org.

You will also need some form of editor in which to write your programs. There
are numerous generic programming editors available for different operating systems
with VIM on Linux, Notepad++ on Windows and Sublime Text on Windows and
Macs being popular choices.
Preface ix

However, using a IDE (Integrated Development Environment) editor such as


PyCharm can make writing and running your programs much easier.
However, this book doesn’t assume any particular editor, IDE or environment
(other than Python 3 itself).

Python Versions

Currently there are two main versions of Python called Python 2 and Python 3.
• Python 2 was launched in October 2000 and has been, and still is, very widely used.
• Python 3 was launched in December 2008 and is a major revision to the lan-
guage that is not backward compatible.
The issues between the two versions can be highlighted by the simple print
facility:
• In Python 2 this is written as print ‘Hello World’
• In Python 3 this is written as print (‘Hello World’)
It may not look like much of a difference but the inclusion of the ‘()’ marks a
major change and means that any code written for one version of Python will
probably not run on the other version. There are tools available, such as the 2to3
utility, that will (partially) automate translation from Python 2 to Python 3 but in
general you are still left with significant work to do.
This then raises the question which version to use?
Although interest in Python 3 is steadily increasing there are many organisations
that are still using Python 2. Choosing which version to use is a constant concern
for many companies.
However, the Python 2 end of life plan was initially announced back in 2015 and
although it has been postponed to 2020 out of concern that a large body of existing
code could not easily be forward-ported to Python 3, it is still living on borrowed
time. Python 3 is the future of the Python language and it is this version that has
introduced many of the new and improved language and library features (that have
admittedly been back ported to Python 2 in many cases). This book is solely
focussed on Python 3.

Useful Python Resources

There are a wide range of resources on the web for Python; we will highlight a few
here that you should bookmark. We will not keep referring to these to avoid
repetition but you can refer back to this section whenever you need to:
• https://en.wikipedia.org/wiki/Python_Software_Foundation Python Software
Foundation.
x Preface

• https://docs.python.org/3/ The main Python 3 documentation site. It contains


tutorials, library references, set up and installation guides as well as Python
how-tos.
• https://docs.python.org/3/library/index.html A list of all the builtin features for
the Python language—this is where you can find online documentation for the
various class and functions that we will be using throughout this book.
• https://pymotw.com/3/ the Python 3 Module of the week site. This site contains
many, many Python modules with short examples and explanations of what the
modules do. A Python module is a library of features that build on and expand
the core Python language. For example, if you are interested in building games
using Python then pygame is a module specifically designed to make this easier.
• https://www.fullstackpython.com/email.html is a monthly newsletter that
focusses on a single Python topic each month, such as a new library or module.
• http://www.pythonweekly.com/ is a free weekly summary of the latest Python
articles, projects, videos and upcoming events.
Each section of the book will provide additional online references relevant to the
topic being discussed.

Conventions

Throughout this book you will find a number of conventions used for text styles.
These text styles distinguish between different kinds of information.
Code words, variable and Python values, used within the main body of the text,
are shown using a Courier font. For example:

This program creates a top level window (the wx.Frame) and gives it a title. It also creates
a label (a wx.StaticText object) to be displayed within the frame.

In the above paragraph wx.Frame and wx.StaticText are classes available in a


Python graphical user interface library.
A block of Python code is set out as shown here:
Preface xi

Note that keywords are shown in bold font.


In some cases something of particular interest may be highlighted with colour:

Any command line or user input is shown in italics and coloured purple; for
example:

Or

Example Code and Sample Solutions

The examples used in this book (along with sample solutions for the exercises at the
end of most chapters) are available in a GitHub repository. GitHub provides a web
interface to Git, as well as a server environment hosting Git.
Git is a version control system typically used to manage source code files (such
as those used to create systems in programming languages such as Python but also
Java, C#, C++, Scala etc.). Systems such as Git are very useful for collaborative
development as they allow multiple people to work on an implementation and to
merge their work together. They also provide a useful historical view of the code
(which also allows developers to roll back changes if modifications prove to be
unsuitable).
If you already have Git installed on your computer then you can clone (obtain a
copy of) the repository locally using:
xii Preface

If you do not have Git then you can obtain a zip file of the examples using

You can of course install Git yourself if you wish. To do this see https://git-scm.
com/downloads. Versions of the Git client for Mac OS, Windows and Linux/Unix
are available here.
However, many IDEs such as PyCharm come with Git support and so offer
another approach to obtaining a Git repository.
For more information on Git see http://git-scm.com/doc. This Git guide provides
a very good primer and is highly recommended.

Acknowledgements I would like to thank Phoebe Hunt for creating the pixel images used for the
StarshipMeteors game in Chap. 8.
Contents

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Part I Computer Graphics


2 Introduction to Computer Graphics . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 The Graphical Computer Era . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Interactive and Non Interactive Graphics . . . . . . . . . . . . . . . . 7
2.5 Pixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.6 Bit Map Versus Vector Graphics . . . . . . . . . . . . . . . . . . . . . . 10
2.7 Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.8 Python and Computer Graphics . . . . . . . . . . . . . . . . . . . . . . . 10
2.9 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3 Python Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 The Turtle Graphics Library . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2.1 The Turtle Module . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2.2 Basic Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . 14
3.2.3 Drawing Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.4 Filling Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3 Other Graphics Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4 3D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.4.1 PyOpenGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

xiii
xiv Contents

4 Computer Generated Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


4.1 Creating Computer Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2 A Computer Art Generator . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.3 Fractals in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3.1 The Koch Snowflake . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3.2 Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.4 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5 Introduction to Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.2 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.3 Plot Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.4 Matplotlib Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.4.1 Backend Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.4.2 The Artist Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4.3 The Scripting Layer . . . . . . . . . . . . . . . . . . . . . . . . 41
5.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6 Graphing with Matplotlib pyplot . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.2 The pyplot API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.3 Line Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
6.3.1 Coded Format Strings . . . . . . . . . . . . . . . . . . . . . . . 46
6.4 Scatter Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
6.4.1 When to Use Scatter Graphs . . . . . . . . . . . . . . . . . . 49
6.5 Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.5.1 Expanding Segments . . . . . . . . . . . . . . . . . . . . . . . . 52
6.5.2 When to Use Pie Charts . . . . . . . . . . . . . . . . . . . . . 53
6.6 Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
6.6.1 Horizontal Bar Charts . . . . . . . . . . . . . . . . . . . . . . . 55
6.6.2 Coloured Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.6.3 Stacked Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . 57
6.6.4 Grouped Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . 58
6.7 Figures and Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
6.8 3D Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7 Graphical User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.2 GUIs and WIMPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Contents xv

7.3 Windowing Frameworks for Python . . . . . . . . . . . . . . . . . . . . 69


7.3.1 Platform-Independent GUI Libraries . . . . . . . . . . . . . 70
7.3.2 Platform-Specific GUI Libraries . . . . . . . . . . . . . . . . 70
7.4 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
8 The wxPython GUI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
8.1 The wxPython Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
8.1.1 wxPython Modules . . . . . . . . . . . . . . . . . . . . . . . . . 74
8.1.2 Windows as Objects . . . . . . . . . . . . . . . . . . . . . . . . 75
8.1.3 A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.2 The wx.App Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
8.3 Window Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
8.4 Widget/Control Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
8.5 Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.6 Arranging Widgets Within a Container . . . . . . . . . . . . . . . . . . 82
8.7 Drawing Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
8.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.9.1 Simple GUI Application . . . . . . . . . . . . . . . . . . . . . 86
9 Events in wxPython User Interfaces . . . . . . . . . .. . . . . . . . . . . . . . 87
9.1 Event Handling . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 87
9.2 Event Definitions . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 87
9.3 Types of Events . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 88
9.4 Binding an Event to an Event Handler . . . .. . . . . . . . . . . . . . 89
9.5 Implementing Event Handling . . . . . . . . . .. . . . . . . . . . . . . . 89
9.6 An Interactive wxPython GUI . . . . . . . . . .. . . . . . . . . . . . . . 92
9.7 Online Resources . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 96
9.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 96
9.8.1 Simple GUI Application . . . . . . .. . . . . . . . . . . . . . 96
9.8.2 GUI Interface to a Tic Tac Toe Game . . . . . . . . . . . 98
10 PyDraw wxPython Example Application . . . . . . . . . . . . . . . . . . . . . 99
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.2 The PyDraw Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.3 The Structure of the Application . . . . . . . . . . . . . . . . . . . . . . 100
10.3.1 Model, View and Controller Architecture . . . . . . . . . 101
10.3.2 PyDraw MVC Architecture . . . . . . . . . . . . . . . . . . . 102
10.3.3 Additional Classes . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.3.4 Object Relationships . . . . . . . . . . . . . . . . . . . . . . . . 104
10.4 The Interactions Between Objects . . . . . . . . . . . . . . . . . . . . . 105
10.4.1 The PyDrawApp . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.4.2 The PyDrawFrame Constructor . . . . . . . . . . . . . . . . 106
xvi Contents

10.4.3 Changing the Application Mode . . . . . . . . . . . . . . . 106


10.4.4 Adding a Graphic Object . . . . . . . . . . . . . . . . . . . . 107
10.5 The Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.5.1 The PyDrawConstants Class . . . . . . . . . . . . . . . . . . 108
10.5.2 The PyDrawFrame Class . . . . . . . . . . . . . . . . . . . . . 109
10.5.3 The PyDrawMenuBar Class . . . . . . . . . . . . . . . . . . 110
10.5.4 The PyDrawToolBar Class . . . . . . . . . . . . . . . . . . . 111
10.5.5 The PyDrawController Class . . . . . . . . . . . . . . . . . . 111
10.5.6 The DrawingModel Class . . . . . . . . . . . . . . . . . . . . 113
10.5.7 The DrawingPanel Class . . . . . . . . . . . . . . . . . . . . . 113
10.5.8 The DrawingController Class . . . . . . . . . . . . . . . . . . 114
10.5.9 The Figure Class . . . . . . . . . . . . . . . . . . . . . . . . . . 115
10.5.10 The Square Class . . . . . . . . . . . . . . . . . . . . . . . . . . 115
10.5.11 The Circle Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
10.5.12 The Line Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
10.5.13 The Text Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.6 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Part II Computer Games


11 Introduction to Games Programming . . . . . . . . . . . . . . . . . . . . . . . 121
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
11.2 Games Frameworks and Libraries . . . . . . . . . . . . . . . . . . . . . 121
11.3 Python Games Development . . . . . . . . . . . . . . . . . . . . . . . . . 122
11.4 Using Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
11.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
12 Building Games with pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
12.2 The Display Surface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
12.3 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12.3.1 Event Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12.3.2 Event Information . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.3.3 The Event Queue . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.4 A First pygame Application . . . . . . . . . . . . . . . . . . . . . . . . . . 130
12.5 Further Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
12.6 A More Interactive pygame Application . . . . . . . . . . . . . . . . . 136
12.7 Alternative Approach to Processing Input Devices . . . . . . . . . 138
12.8 pygame Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
12.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Contents xvii

13 StarshipMeteors pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141


13.1 Creating a Spaceship Game . . . . . . . . . . . . . . . . . . . . . . . . . . 141
13.2 The Main Game Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
13.3 The GameObject Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
13.4 Displaying the Starship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
13.5 Moving the Spaceship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
13.6 Adding a Meteor Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
13.7 Moving the Meteors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.8 Identifying a Collision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.9 Identifying a Win . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
13.10 Increasing the Number of Meteors . . . . . . . . . . . . . . . . . . . . . 154
13.11 Pausing the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.12 Displaying the Game Over Message . . . . . . . . . . . . . . . . . . . . 156
13.13 The StarshipMeteors Game . . . . . . . . . . . . . . . . . . . . . . . . . . 157
13.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
13.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Part III Testing


14 Introduction to Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
14.2 Types of Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
14.3 What Should Be Tested? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
14.4 Testing Software Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
14.4.1 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
14.4.2 Integration Testing . . . . . . . . . . . . . . . . . . . . . . . . . 169
14.4.3 System Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
14.4.4 Installation/Upgrade Testing . . . . . . . . . . . . . . . . . . 170
14.4.5 Smoke Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
14.5 Automating Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
14.6 Test Driven Development . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
14.6.1 The TDD Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
14.6.2 Test Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.6.3 Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.7 Design for Testability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.7.1 Testability Rules of Thumb . . . . . . . . . . . . . . . . . . . 173
14.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
14.9 Book Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
15 PyTest Testing Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
15.2 What Is PyTest? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
15.3 Setting Up PyTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
15.4 A Simple PyTest Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
xviii Contents

15.5 Working with PyTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179


15.6 Parameterised Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
15.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
15.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
16 Mocking for Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
16.2 Why Mock? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
16.3 What Is Mocking? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
16.4 Common Mocking Framework Concepts . . . . . . . . . . . . . . . . 191
16.5 Mocking Frameworks for Python . . . . . . . . . . . . . . . . . . . . . . 192
16.6 The unittest.mock Library . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
16.6.1 Mock and Magic Mock Classes . . . . . . . . . . . . . . . . 193
16.6.2 The Patchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
16.6.3 Mocking Returned Objects . . . . . . . . . . . . . . . . . . . 195
16.6.4 Validating Mocks Have Been Called . . . . . . . . . . . . 196
16.7 Mock and MagicMock Usage . . . . . . . . . . . . . . . . . . . . . . . . 197
16.7.1 Naming Your Mocks . . . . . . . . . . . . . . . . . . . . . . . 197
16.7.2 Mock Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
16.7.3 Attributes on Mock Classes . . . . . . . . . . . . . . . . . . . 198
16.7.4 Mocking Constants . . . . . . . . . . . . . . . . . . . . . . . . . 199
16.7.5 Mocking Properties . . . . . . . . . . . . . . . . . . . . . . . . . 199
16.7.6 Raising Exceptions with Mocks . . . . . . . . . . . . . . . . 199
16.7.7 Applying Patch to Every Test Method . . . . . . . . . . . 200
16.7.8 Using Patch as a Context Manager . . . . . . . . . . . . . 200
16.8 Mock Where You Use It . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
16.9 Patch Order Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
16.10 How Many Mocks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
16.11 Mocking Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
16.12 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
16.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

Part IV File Input/Output


17 Introduction to Files, Paths and IO . . . . . . . . . . . . . . . . . . . . . . . . . 207
17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
17.2 File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
17.3 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
17.4 File Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
17.5 Sequential Access Versus Random Access . . . . . . . . . . . . . . . 213
17.6 Files and I/O in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
17.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Contents xix

18 Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215


18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
18.2 Obtaining References to Files . . . . . . . . . . . . . . . . . . . . . . . . 215
18.3 Reading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
18.4 File Contents Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
18.5 Writing Data to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
18.6 Using Files and with Statements . . . . . . . . . . . . . . . . . . . . . . 219
18.7 The Fileinput Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
18.8 Renaming Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
18.9 Deleting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
18.10 Random Access Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
18.11 Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
18.12 Temporary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
18.13 Working with Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
18.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
18.15 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
19 Stream IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
19.2 What is a Stream? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
19.3 Python Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
19.4 IOBase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
19.5 Raw IO/UnBuffered IO Classes . . . . . . . . . . . . . . . . . . . . . . . 234
19.6 Binary IO/Buffered IO Classes . . . . . . . . . . . . . . . . . . . . . . . . 234
19.7 Text Stream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
19.8 Stream Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
19.9 Closing Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
19.10 Returning to the open() Function . . . . . . . . . . . . . . . . . . . . . . 238
19.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
19.12 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
20 Working with CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
20.2 CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
20.2.1 The CSV Writer Class . . . . . . . . . . . . . . . . . . . . . . 242
20.2.2 The CSV Reader Class . . . . . . . . . . . . . . . . . . . . . . 243
20.2.3 The CSV DictWriter Class . . . . . . . . . . . . . . . . . . . 244
20.2.4 The CSV DictReader Class . . . . . . . . . . . . . . . . . . . 245
20.3 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
20.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
21 Working with Excel Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
21.2 Excel Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
xx Contents

21.3 The Openpyxl. Workbook Class . . . . . . . . . . . . . . . . . . . . . . 250


21.4 The Openpyxl. WorkSheet Objects . . . . . . . . . . . . . . . . . . . . . 250
21.5 Working with Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
21.6 Sample Excel File Creation Application . . . . . . . . . . . . . . . . . 251
21.7 Loading a Workbook from an Excel File . . . . . . . . . . . . . . . . 253
21.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
21.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
22 Regular Expressions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
22.2 What Are Regular Expressions? . . . . . . . . . . . . . . . . . . . . . . . 257
22.3 Regular Expression Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . 258
22.3.1 Pattern Metacharacters . . . . . . . . . . . . . . . . . . . . . . 259
22.3.2 Special Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . 259
22.3.3 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
22.4 The Python re Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
22.5 Working with Python Regular Expressions . . . . . . . . . . . . . . . 261
22.5.1 Using Raw Strings . . . . . . . . . . . . . . . . . . . . . . . . . 261
22.5.2 Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
22.5.3 The Match Object . . . . . . . . . . . . . . . . . . . . . . . . . . 262
22.5.4 The search() Function . . . . . . . . . . . . . . . . . . . . . . . 263
22.5.5 The match() Function . . . . . . . . . . . . . . . . . . . . . . . 264
22.5.6 The Difference Between Matching and Searching . . . 265
22.5.7 The findall() Function . . . . . . . . . . . . . . . . . . . . . . . 265
22.5.8 The finditer() Function . . . . . . . . . . . . . . . . . . . . . . 266
22.5.9 The split() Function . . . . . . . . . . . . . . . . . . . . . . . . 266
22.5.10 The sub() Function . . . . . . . . . . . . . . . . . . . . . . . . . 267
22.5.11 The compile() Function . . . . . . . . . . . . . . . . . . . . . . 268
22.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
22.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

Part V Database Access


23 Introduction to Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
23.2 What Is a Database? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
23.2.1 Data Relationships . . . . . . . . . . . . . . . . . . . . . . . . . 276
23.2.2 The Database Schema . . . . . . . . . . . . . . . . . . . . . . . 277
23.3 SQL and Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
23.4 Data Manipulation Language . . . . . . . . . . . . . . . . . . . . . . . . . 280
23.5 Transactions in Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
23.6 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Contents xxi

24 Python DB-API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283


24.1 Accessing a Database from Python . . . . . . . . . . . . . . . . . . . . 283
24.2 The DB-API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
24.2.1 The Connect Function . . . . . . . . . . . . . . . . . . . . . . . 284
24.2.2 The Connection Object . . . . . . . . . . . . . . . . . . . . . . 284
24.2.3 The Cursor Object . . . . . . . . . . . . . . . . . . . . . . . . . 285
24.2.4 Mappings from Database Types to Python Types . . . 286
24.2.5 Generating Errors . . . . . . . . . . . . . . . . . . . . . . . . . . 286
24.2.6 Row Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . 287
24.3 Transactions in PyMySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
24.4 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
25 PyMySQL Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
25.1 The PyMySQL Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
25.2 Working with the PyMySQL Module . . . . . . . . . . . . . . . . . . . 291
25.2.1 Importing the Module . . . . . . . . . . . . . . . . . . . . . . . 292
25.2.2 Connect to the Database . . . . . . . . . . . . . . . . . . . . . 292
25.2.3 Obtaining the Cursor Object . . . . . . . . . . . . . . . . . . 293
25.2.4 Using the Cursor Object . . . . . . . . . . . . . . . . . . . . . 293
25.2.5 Obtaining Information About the Results . . . . . . . . . 294
25.2.6 Fetching Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
25.2.7 Close the Connection . . . . . . . . . . . . . . . . . . . . . . . 295
25.3 Complete PyMySQL Query Example . . . . . . . . . . . . . . . . . . . 295
25.4 Inserting Data to the Database . . . . . . . . . . . . . . . . . . . . . . . . 296
25.5 Updating Data in the Database . . . . . . . . . . . . . . . . . . . . . . . . 298
25.6 Deleting Data in the Database . . . . . . . . . . . . . . . . . . . . . . . . 299
25.7 Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
25.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
25.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301

Part VI Logging
26 Introduction to Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
26.2 Why Log? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
26.3 What Is the Purpose of Logging? . . . . . . . . . . . . . . . . . . . . . . 306
26.4 What Should You Log? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
26.5 What Not to Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
26.6 Why Not Just Use Print? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
26.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
27 Logging in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
27.1 The Logging Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
27.2 The Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
xxii Contents

27.3 Controlling the Amount of Information Logged . . . . . . . . . . . 313


27.4 Logger Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
27.5 Default Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
27.6 Module Level Loggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
27.7 Logger Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
27.8 Formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
27.8.1 Formatting Log Messages . . . . . . . . . . . . . . . . . . . . 319
27.8.2 Formatting Log Output . . . . . . . . . . . . . . . . . . . . . . 319
27.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
27.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
28 Advanced Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
28.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
28.2 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
28.2.1 Setting the Root Output Handler . . . . . . . . . . . . . . . 325
28.2.2 Programmatically Setting the Handler . . . . . . . . . . . 326
28.2.3 Multiple Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . 328
28.3 Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
28.4 Logger Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
28.5 Performance Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . 333
28.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334

Part VII Concurrency and Parallelism


29 Introduction to Concurrency and Parallelism . . . . . . . . . . . . . . . . . 337
29.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
29.2 Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
29.3 Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
29.4 Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
29.5 Grid Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
29.6 Concurrency and Synchronisation . . . . . . . . . . . . . . . . . . . . . 342
29.7 Object Orientation and Concurrency . . . . . . . . . . . . . . . . . . . . 342
29.8 Threads V Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
29.9 Some Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
29.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
30 Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
30.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
30.2 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
30.3 Thread States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
30.4 Creating a Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
30.5 Instantiating the Thread Class . . . . . . . . . . . . . . . . . . . . . . . . 349
30.6 The Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Contents xxiii

30.7 The Threading Module Functions . . . . . . . . . . . . . . . . . . . . . . 352


30.8 Passing Arguments to a Thread . . . . . . . . . . . . . . . . . . . . . . . 352
30.9 Extending the Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . 354
30.10 Daemon Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
30.11 Naming Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
30.12 Thread Local Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
30.13 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
30.14 The Global Interpreter Lock . . . . . . . . . . . . . . . . . . . . . . . . . . 359
30.15 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
30.16 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
31 Multiprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
31.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
31.2 The Process Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
31.3 Working with the Process Class . . . . . . . . . . . . . . . . . . . . . . . 365
31.4 Alternative Ways to Start a Process . . . . . . . . . . . . . . . . . . . . 366
31.5 Using a Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
31.6 Exchanging Data Between Processes . . . . . . . . . . . . . . . . . . . 372
31.7 Sharing State Between Processes . . . . . . . . . . . . . . . . . . . . . . 374
31.7.1 Process Shared Memory . . . . . . . . . . . . . . . . . . . . . 374
31.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
31.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
32 Inter Thread/Process Synchronisation . . . . . . . . . . . . . . . . . . . . . . . 377
32.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
32.2 Using a Barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
32.3 Event Signalling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
32.4 Synchronising Concurrent Code . . . . . . . . . . . . . . . . . . . . . . . 382
32.5 Python Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
32.6 Python Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
32.7 Python Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
32.8 The Concurrent Queue Class . . . . . . . . . . . . . . . . . . . . . . . . . 389
32.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
32.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
33 Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
33.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
33.2 The Need for a Future . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
33.3 Futures in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
33.3.1 Future Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
33.3.2 Simple Example Future . . . . . . . . . . . . . . . . . . . . . . 397
33.4 Running Multiple Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
33.4.1 Waiting for All Futures to Complete . . . . . . . . . . . . 400
33.4.2 Processing Results as Completed . . . . . . . . . . . . . . . 402
xxiv Contents

33.5 Processing Future Results Using a Callback . . . . . . . . . . . . . . 403


33.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
33.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
34 Concurrency with AsyncIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
34.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
34.2 Asynchronous IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
34.3 Async IO Event Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
34.4 The Async and Await Keywords . . . . . . . . . . . . . . . . . . . . . . 409
34.4.1 Using Async and Await . . . . . . . . . . . . . . . . . . . . . 409
34.5 Async IO Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
34.6 Running Multiple Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
34.6.1 Collating Results from Multiple Tasks . . . . . . . . . . . 414
34.6.2 Handling Task Results as They Are Made
Available . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
34.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
34.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417

Part VIII Reactive Programming


35 Reactive Programming Introduction . . . . . . . . . . . . . . . . . . . . . . . . 421
35.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
35.2 What Is a Reactive Application? . . . . . . . . . . . . . . . . . . . . . . 421
35.3 The ReactiveX Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
35.4 The Observer Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
35.5 Hot and Cold Observables . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
35.5.1 Cold Observables . . . . . . . . . . . . . . . . . . . . . . . . . . 424
35.5.2 Hot Observables . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
35.5.3 Implications of Hot and Cold Observables . . . . . . . . 424
35.6 Differences Between Event Driven Programming and
Reactive Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
35.7 Advantages of Reactive Programming . . . . . . . . . . . . . . . . . . 425
35.8 Disadvantages of Reactive Programming . . . . . . . . . . . . . . . . 426
35.9 The RxPy Reactive Programming Framework . . . . . . . . . . . . . 426
35.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
35.11 Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
36 RxPy Observables, Observers and Subjects . . . . . . . . . . . . . . . . . . 429
36.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
36.2 Observables in RxPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
36.3 Observers in RxPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
36.4 Multiple Subscribers/Observers . . . . . . . . . . . . . . . . . . . . . . . 432
36.5 Subjects in RxPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
Contents xxv

36.6 Observer Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435


36.6.1 Available Schedulers . . . . . . . . . . . . . . . . . . . . . . . . 437
36.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
36.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
37 RxPy Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
37.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
37.2 Reactive Programming Operators . . . . . . . . . . . . . . . . . . . . . . 439
37.3 Piping Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
37.4 Creational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
37.5 Transformational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 441
37.6 Combinatorial Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
37.7 Filtering Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
37.8 Mathematical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
37.9 Chaining Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
37.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
37.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448

Part IX Network Programming


38 Introduction to Sockets and Web Services . . . . . . . . . . . . . . . . . . . 451
38.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
38.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
38.3 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
38.4 Addressing Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
38.5 Localhost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
38.6 Port Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
38.7 IPv4 Versus IPv6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
38.8 Sockets and Web Services in Python . . . . . . . . . . . . . . . . . . . 455
38.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
39 Sockets in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
39.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
39.2 Socket to Socket Communication . . . . . . . . . . . . . . . . . . . . . . 457
39.3 Setting Up a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
39.4 An Example Client Server Application . . . . . . . . . . . . . . . . . . 458
39.4.1 The System Structure . . . . . . . . . . . . . . . . . . . . . . . 458
39.4.2 Implementing the Server Application . . . . . . . . . . . . 459
39.5 Socket Types and Domains . . . . . . . . . . . . . . . . . . . . . . . . . . 461
39.6 Implementing the Client Application . . . . . . . . . . . . . . . . . . . 461
39.7 The Socketserver Module . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
39.8 HTTP Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
39.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
39.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
xxvi Contents

40 Web Services in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471


40.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
40.2 RESTful Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
40.3 A RESTful API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
40.4 Python Web Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
40.5 Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
40.6 Hello World in Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
40.6.1 Using JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
40.6.2 Implementing a Flask Web Service . . . . . . . . . . . . . 475
40.6.3 A Simple Service . . . . . . . . . . . . . . . . . . . . . . . . . . 475
40.6.4 Providing Routing Information . . . . . . . . . . . . . . . . 476
40.6.5 Running the Service . . . . . . . . . . . . . . . . . . . . . . . . 477
40.6.6 Invoking the Service . . . . . . . . . . . . . . . . . . . . . . . . 478
40.6.7 The Final Solution . . . . . . . . . . . . . . . . . . . . . . . . . 479
40.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
41 Bookshop Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
41.1 Building a Flask Bookshop Service . . . . . . . . . . . . . . . . . . . . 481
41.2 The Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
41.3 The Domain Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
41.4 Encoding Books Into JSON . . . . . . . . . . . . . . . . . . . . . . . . . . 484
41.5 Setting Up the GET Services . . . . . . . . . . . . . . . . . . . . . . . . . 486
41.6 Deleting a Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
41.7 Adding a New Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
41.8 Updating a Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
41.9 What Happens if We Get It Wrong? . . . . . . . . . . . . . . . . . . . 492
41.10 Bookshop Services Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
41.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
Chapter 1
Introduction

1.1 Introduction

I have heard many people over the years say that Python is an easy language to lean
and that Python is also a simple language.
To some extent both of these statements are true; but only to some extent.
While the core of the Python language is easy to lean and relatively simple (in
part thanks to its consistency); the sheer richness of the language constructs and
flexibility available can be overwhelming. In addition the Python environment, its
eco system, the range of libraries available, the often competing options available
etc., can make moving to the next level daunting.
Once you have learned the core elements of the language such as how classes
and inheritance work, how functions work, what are protocols and Abstract Base
Classes etc. Where do you go next?
The aim of this book is to delve into those next steps. The book is organised into
eight different topics:
1. Computer Graphics. The book covers Computer Graphics and Computer
Generated Art in Python as well as Graphical User Interfaces and Graphing/
Charting via MatPlotLib.
2. Games Programming. This topic is covered using the pygame library.
3. Testing and Mocking. Testing is an important aspect of any software devel-
opment; this book introduces testing in general and the PyTest module in detail.
It also considers mocking within testing including what and when to mock.
4. File Input/Output. The book covers text file reading and writing as well as
reading and writing CSV and Excel files. Although not strictly related to file
input, regulator expressions are included in this section as they can be used to
process textual data held in files.
5. Database Access. The book introduces databases and relational database in
particular. It then presents the Python DB-API database access standard and

© Springer Nature Switzerland AG 2019 1


J. Hunt, Advanced Guide to Python 3 Programming,
Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-030-25943-3_1
2 1 Introduction

one implementation of this standard, the PyMySQL module used to access a


MySQL database.
6. Logging. An often missed topic is that of logging. The book therefore intro-
duces logging the need for logging, what to log and what not to log as well as
the Python logging module.
7. Concurrency and Parallelism. The book provides extensive coverage of
concurrency topics including Threads, Processes and inter thread or process
synchronisation. It also presents Futures and AsyncIO.
8. Reactive Programming. This section of the book introduces Reactive
Programming using the PyRx reactive programming library.
9. Network Programming. The book concludes by introducing socket and web
service communications in Python.
Each section is introduced by a chapter providing the background and key
concepts of that topic. Subsequent chapters then cover various aspects of the topic.
For example, the first topic covered is on Computer Graphics. This section has
an introductory chapter on Computer Graphics in general. It then introduces the
Turtle Graphics Python library which can be used to generate a graphical display.
The following chapter considers the subject of Computer Generated Art and uses
the Turtle Graphics library to illustrate these ideas. Thus several examples are
presented that might be considered art. The chapter concludes by presenting the
well known Koch Snowflake and the Mandelbrot Fractal set.
This is followed by a chapter presenting the MatPlotLib library used for gen-
erating 2D and 3D charts and graphs (such as a line chart, bar chart or scatter
graph).
The section concludes with a chapter on Graphical User Interfaces (or GUIs)
using the wxpython library. This chapter explores what we mean by a GUI and
some of the alternatives available in Python for creating a GUI.
Subsequent topics follow a similar pattern.
Each programming or library oriented chapter also includes numerous sample
programs that can be downloaded from the GutHub repository and executed. These
chapters also include one or more end of chapter exercises (with sample solutions
also in the GutHub repository).
The topics within the book can be read mostly independently of each other. This
allows the reader to dip into subject areas as and when required. For example, the
File Input/Output section and the Database Access section can be read indepen-
dently of each other (although in this case assessing both technologies may be
useful in selecting an appropriate approach to adopt for the long term persistent
storage of data in a particular system).
Within each section there are usually dependencies, for example it is necessary
to understand the pygame library from the ‘Building Games with pygame’
introductory chapter, before exploring the worked case study presented by the
chapter on the StarshipMeteors game. Similarly it is necessary to have read the
Threading and Multiprocessing chapters before reading the Inter Thread/Process
Synchronisation chapter.
Part I
Computer Graphics
Another random document with
no related content on Scribd:
The Project Gutenberg eBook of Don Sebastian
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: Don Sebastian


or, The house of the Braganza: An historical romance.
vol. 2

Author: Anna Maria Porter

Release date: July 28, 2022 [eBook #68608]

Language: English

Original publication: United Kingdom: Longman, Hurst, Rees,


and Orme, 1809

Credits: Sonya Schermann and the Online Distributed


Proofreading Team at https://www.pgdp.net (This file
was produced from images generously made available
by The Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK DON


SEBASTIAN ***
Contents.
CHAP. I., CHAP. II., CHAP. III.,
CHAP. IV., CHAP. V., CHAP. VI.,
CHAP. VII., CHAP. VIII.
Some typographical errors have
been corrected; a list follows the
text.
(etext transcriber's note)

DON SEBASTIAN;

OR,

THE HOUSE OF BRAGANZA.

J. M‘CREERY,Printer,
Black-Horse-Court, Fleet-Street, London.
DON SEBASTIAN;

OR,

THE HOUSE OF BRAGANZA.


AN HISTORICAL ROMANCE.

IN FOUR VOLUMES.

BY MISS ANNA MARIA PORTER.

AUTHOR OF THE HUNGARIAN BROTHERS.

Take Physic, Pomp!


Expose thyself to feel what wretches feel,
So shalt thou shake the superflux to them,
And shew the Heavens more just.
King Lear.

VOL. II.
LONDON:

PRINTED FOR LONGMAN, HURST, REES, AND ORME,


PATERNOSTER ROW.
———
1809.
DON SEBASTIAN,
OR

THE HOUSE OF BRAGANZA.


CHAP. I.
The first day on which Gaspar was able to walk out, Sebastian obtained
leave for him to breathe the air of the gardens in the cool of evening: all the
slaves were retired to supper, when the grateful soldier hesitatingly accepted
the support of his King, and slowly proceeded from his chamber.
“At moments like these,” whispered he, “I cannot believe myself awake.
—So supported—so attended,—oh sire! in Portugal this would have been
impossible.”
“Only because in Portugal I should not have known your value.”
Sebastian could not forbear sighing as he spoke—but quickly smiling, he
added, “Trust me, Gaspar, I shall not feel less a King when again seated on
the throne of my ancestors, for having administered to your sufferings and
shewn my gratitude for your rare attachment. I take your heart as a sample
of all my people’s; and the reflections your generous sensibilities have
given rise to, shall teach me to respect their feelings, though at the expense
of my own extravagant desires.”
They now moved slowly on: a gentle breeze just stirred the leaves of the
umbrageous plane trees, mingling their murmurs with the cooling sound of
fountains and water-falls; a balmy smell from fruits and flowers delighted
the senses of Gaspar; his eyes wandered with pleasure over the beautiful
gardens, and the consciousness of reviving health diffused through his heart
and over his face an air of grateful complacency. His pale cheek and feeble
frame presented an interesting contrast to the yet vigorous youth of
Sebastian: like a young cedar of Libanus, flourishing in eternal spring, his
manly beauty seemed formed for duration.
Having conducted Gaspar into the labyrinth, the King laid him down
upon one of its mossy couches; fearing to exhaust him by conversation, he
took out his flute, and played several soft airs.
The music, the profound tranquillity, and his extreme weakness, by
degrees stole upon the senses of Gaspar; and he dropt to sleep: Sebastian
observed it in silence; then fearing to awake him, rose to seek some other
slave who might assist in conveying him to his chamber.
For this purpose he quitted the labyrinth: the pale evening star twinkling
through innumerous boughs, alone lighted him on his way. Glowing with
benevolent and friendly joy, he trod with a lighter step, and looked even in
the gardens of El Hader as he had done in the magnificent precincts of
Xabregas: though wrapt in a homely dress, the kingly air was still visible.
There is a gracefulness of mind which ennobles the meanest habit; that
grace now gave picturesque grandeur to the coarse drapery of Sebastian.
His neck and head were bare; but the crown of Portugal itself, could not
have added majesty to that commanding brow, nature’s hand had encircled
it with a crown: his dark brown hair glowing with living gold, hung in
glossy curls over his forehead and his cheek, discovering at intervals, as the
breeze lifted it, those eyes and that mouth whose sweetness had once been
proverbial in a court.
Hastening onwards, he was startled by the sight of Kara Aziek standing
alone, as if she had been listening to the sound of his flute: after an instant’s
confusion, the impetuous monarch flung himself at her feet, and uttered in
Moresco a hasty expression of gratitude, then remembering what Hafiz had
said of her accomplishments, and fearing to be overheard, he changed his
accent, and spoke to her in Italian.
She answered him courteously, though not fluently, in the same
language; but her soft voice was so broken by timidity, so mixed with sighs,
and interrupted by hesitation, that she was scarcely intelligible. Sebastian
remained at her feet, and she had time to recover herself.
“What is it I can do for thee, amiable Christian?” she resumed, “my heart
is touched with thy situation.—So young, so brave, so generous as I hear
thou art, thou must have many friends in thine own country, the
remembrance of whom increases thy present sorrow: would I could restore
thee to them! but I cannot; my power extends only to ameliorating thy
condition.—What is it I can do for thee?”
“Alas, nothing!” exclaimed the King, pierced with disappointment,
“banished from my country, without hope of return, I no longer desire life. I
was born, lady, in the midst of power, riches, and honors; I had the means
and the will of blessing multitudes; I was surrounded by relations and
friends. I am now a slave! if forced at last to abandon the hope of release,
do you imagine that any thing can reconcile me to such a destiny? To your
heavenly goodness I already owe all the comfort of which my miserable
fate is susceptible: ah! could I persuade you to pity me yet further—to
procure for me permission to inform one friend of my captivity, and so be
ransomed from the Almoçadem!”
“Christian!” said Kara Aziek, after a pause, “thy noble disregard of
selfish considerations since thou hast been under the charge of Hafiz,
deserves the exertions of all who love virtue; be assured, from this moment,
that thou hast made a friend in Kara Aziek: she will continue to protect
thee, she will cautiously labour to obtain thy release; but thou must not be
impatient if the time be long, and the object lost. My father will not bear
either too frequent or too earnest urging: if I would serve the Christians, I
must do it prudently.”
Sebastian put the embroidered hem of her kaftan to his lips: “You are my
guardian angel, he exclaimed, and there are hearts in Portugal worthy of
knowing yours, that shall one day bless you!”
The young monarch’s emotion interested Kara Aziek, she wished to see
him again more distinctly, and for this purpose lifted up her veil; the instant
their eyes met, she dropt it with a modest blush. But her soft beauty, like
that of the summer moon, instantaneously changed the impetuous ardour of
Sebastian; a serene and delightful admiration succeeded to his agitation; her
shape, her voice, her countenance, were all lovely, they breathed the
tenderness and the purity of an angel, and though the radient image of
Donna Gonsalva outshone the Moorish Beauty in splendor, it could only
have been preferred by a lover.
Every thing in Gonsalva was gay, resistless, triumphant; in Kara Aziek,
touching, yielding, and humble; the one seemed a divinity to be
worshipped, the other a tender creature to be loved.
Every endearing quality of woman’s fond and faithful heart, beamed
from the dewy eyes of Kara Aziek; those eyes bespoke a soul capable of
wholly losing itself in the happiness and honour of one beloved object; they
promised heroic devotedness, disinterested goodness, virtuous submission:
they had never yet known how to express disdain, anger, or desire of rule. It
was sufficient to have beheld Kara Aziek but for a moment, to be convinced
that she was the sweetest and the gentlest of human beings.
Lost in the remembrance of a countenance so engaging, the young King
did not remark that his companion heaved several deep sighs: at length, she
spoke to him again. “It is then to Portugal that thou wishest to return? It was
my mother’s country—perhaps thou hast a mother and sisters there—or a
wife—art thou married, Christian?—”
Sebastian answered in the negative with a sigh deeper than her own;
Aziek eagerly resumed. “If thou, hast neither mother, sister, nor wife, thou
should’st not be so very unhappy at thy present misfortune: think how much
keener would have been thy sorrows, had they been increased by the
memory of such beloved relations. Learn to be grateful, Christian, to the
Great Being for his smallest mercies!”
Sebastian was about to own that Portugal contained one as dear to him as
a wife, when she asked after his sick countryman; on hearing that he was
then in the labyrinth, she grieved at having detained his friend, and bade
him pursue his way to the house. “Pray warn this poor fellow,” she added,
“never again to attempt so rash an enterprize: he may get beyond my
father’s walls ’tis true, but wherever he goes he must encounter Moors, or
perish for want among solitary places.—Adieu, Portuguese! endure
patiently, pray often, hope constantly.”—So saying, the lovely Moor turned
away, leaving Sebastian standing where they had first met.
He could not forbear ejaculating a thanksgiving for this fortunate
meeting, which licensed him in all those sanguine expectations that
otherwise had been fantastic: he blessed the amiable Aziek repeatedly,
while hastening to the hall of the household slaves, he procured an assistant,
and returned for Gaspar.
The motion, in carrying him, quickly awakened Gaspar, but Sebastian
would not rouse him further by speaking then of his adventure, and shortly
afterwards left him to repose for the night.
The next time Kara Aziek saw the King of Portugal, it was again in the
gardens, supporting his still-languid friend: she stopt in the midst of her
women and asked after the invalid.
Sebastian seized this opportunity of describing his delicate constitution,
and beseeching her to order him some less hazardous labour than that of
working through all weathers in the open air: at the same time he ventured
to solicit indulgence for some other sick captives. Kara Aziek fixed her
luminous eyes on him through her veil, with a look of soft admiration.
“How is it,” she said, “that thou dost never ask any thing for thyself?—
hast thou been taught to live solely for others?”
“It was the first lesson I ever learnt,” replied Sebastian, “would to God,
that I had always practised it! but my heart, lady, has not room at present for
minor wishes; I languish for liberty. While I am a slave, every personal
good is indifferent to me.”
“I pity thee, Christian, indeed I pity thee!” said Aziek in a tone of
touching sincerity, “if I were the sole arbiter of thy fate, of all fates, there is
not a Christian groaning throughout Africa that should remain in his bonds
—but, though my father indulges me beyond what any other parent allows,
he does not leave me absolute. I must win favours from him by degrees;
while thou askest these indulgencies for others, thine own suit remains
unurged: choose then between them and thyself! am I to plead for their
comfort, or thy freedom?”
“For them! for them!” cried Sebastian.
“Generous Christian!” she exclaimed, extending her arm by an
involuntary impulse: Sebastian threw himself at her feet, and ventured to
seize and kiss her hand; it was a hand so lovely soft, that it seemed to melt
in the pressure: though his ardour was chastized by respect, Kara Aziek
drew back in confusion. “I will learn of thee to be generous,” she added, “to
be so, I must risk something, conquer my timid nature, and be importunate
for thy sake.” She then earnestly besought Sebastian to concert some mode
of ameliorating the condition of all the slaves, and yet rendering them
useful to El Hader: if a plan were formed, embracing a variety of objects
suited to different degrees of strength and ingenuity, she thought its
profitableness would recommend it to her father, and make a strong
argument for her to use in urging its adoption.
Delighted with her benevolent idea, Sebastian readily promised to sketch
such a plan with Hafiz, and then to submit it for her approval: he
accompanied this promise with an animated eulogium upon her mind and
heart. At this she blushed timidly, telling him that she owed her
thoughtfulness to a few good books which her mother had taught her to
read, and which perhaps might now be a solace to him: the King was
gladdened by this offer, and gratefully accepted it.
He then ventured to ask whether Kara Aziek could give him any
information about the state of Portugal; she replied with benevolent
minuteness. From her answers he learnt that his throne was filled by the
Cardinal, Don Henry, and that his own supposed body (obtained through the
King of Spain) had been buried at Belem, with royal honours. “Do they
lament their late king?” asked Sebastian, with extreme emotion.
“I hear he was in many things worthy to be regretted,” replied Aziek,
“but his ill-advised enterprize nearly desolated Portugal; for of the few
families he left in it, there was not one that has not lost some relative, either
on the field, or by captivity. In this weight of private grief, I suppose a
public loss is scarcely felt. Thou didst love thy monarch, I think, that
starting tear honours his memory.” The eyes of the gentle Moor filled with
answering tears while she spoke.
Overcome by her obvious remark, Sebastian stifled a groan: again he
saw the bloody plain of Alcazar, and again conscience accused him of
countless murders. Heart-wrung, even to torture, he leaned in silent agony
upon the shoulder of Gaspar, who being ignorant of Italian (in which they
spoke) was now surprized and disturbed at his sovereign’s agitation. Kara
Aziek regarded him with a mixture of terror and pity.
“Alas! what have I said!” she exclaimed, “that has thus afflicted thee?
compose thyself, amiable Christian! thou shalt see thy country again, if
Kara Aziek parts with every comfort of her life to obtain thee that felicity.”
Without waiting to receive his thanks, she withdrew hastily, leaving
Gaspar to make unsuccessful attempts at soothing his royal friend.
Aziek had unconsciously planted the dagger of the furies in the very
bosom she would fain have shielded from every shaft: care for others,
constant occupation, and ceaseless projects of escape, had lately banished
from Sebastian’s mind, all self-accusing recollections; but now he saw at
one glance his name forgotten or execrated in the land which he loved with
parental tenderness, his throne filled by another, his people sunk in funereal
gloom, and Donna Gonsalva learning to hate his name, while she wept for
her murdered father!
These images were heightened to the wildest excess by a passionate
imagination, fruitful in self-tormenting, and as it hurried him in thought
from object to object, he sacredly vowed never again to unsheathe the
sword but in defence, or for the succour of others: this virtuous vow
checked the torrent of sorrow.
The last words of Kara Aziek had escaped his ear; and desperate of
release through her means, (since she herself was so doubtful of it,) he came
to the resolution of making some personal effort for his own deliverance:
warmed by this new project, he gradually recovered himself, and returned
back with Gaspar.
On entering his chamber he found several volumes of Italian and
Portuguese authors, which he took up and looked at, without knowing one
of their titles; for his mind was otherwise occupied, and he laid himself on
his pallet, not to sleep, but to think.
It was now that Sebastian found his first visit to Barbary likely to
produce benefit; by it he was made acquainted with all the coast, and much
of the interior, he had also acquired information from the persons he
redeemed, which now promised to serve him essentially.
In those days the Emperors of Morocco had a right to every captive
beyond a certain rank, taken either in battle, or on the seas, and the Moors
therefore, frequently secreted their noble slaves and conveyed them
privately away for the sake of high ransoms: one of these gentlemen who
was the property of a low man, had been conducted by him to the castle of
Massignan, by a road which the King now tried to recollect. It had lain
through a track of more than a hundred miles: Sebastian calculated on being
able to pursue the same route undiscovered, as it led principally through
desart mountains.
It is true, that before he could reach Massignan, he must cross the river
Ardea, the fords of which were all guarded by Moorish posts, for the
express purpose of frustrating the escape of run-a-ways. But he had been
told of a safe passage in one part where the river narrowed among the
Green mountains, and which on account of its remoteness was left
unwatched: once there, he might cross, and make directly down to the
coast; could he gain Massignan he should be safe.
Neither the savage beasts infesting the country he must thus traverse
unarmed, nor the apprehension of starving, staggered the resolution of
Sebastian; he felt that a mighty spirit has something of omnipotence in it;
and believed that the all-seeing parent who feeds the fowls of the air, would
provide for his limited wants: if he were destined to perish, better to die
free, than to linger out life in slavery.
At first he thought of making Gaspar his companion, but a moment’s
consideration forbade him to indulge so dangerous a wish: Gaspar could not
endure the fatigue and peril to which they must be subjected during such an
enterprize, and would in all probability prove the cause of their eventual re-
capture: better therefore, to hasten to Masignan and from thence send a
King’s offer to El Hader. Long did the generous Sebastian pause upon this
obstacle: he abhorred the appearance of abandoning his friend, and would
not have resolved on it at last, had he not justly deemed that the only
method of procuring his ultimate liberation.
The next object of consideration was how to get beyond the walls of the
Almoçadem: so indulged as he had long been, it seemed almost perfidious
to repay the lenity of El Hader, and the reliance of Hafiz, by using them for
the purpose of escape; yet liberty, sacred liberty, is the birth-right of every
man; and he who would enslave his fellow-man, however softly he may
weave his chains, has perhaps no legitimate claim to his fidelity.
Sebastian felt the force of this assertion: he had ever scorned
dissembling his thirst for freedom, and therefore believed himself still
privileged to attempt obtaining it by any bold measure. Ere he finally
digested this sudden plan, he endeavoured to obey the humane injunction of
Kara Aziek; from the day on which they first met, he had employed himself
after work-hours in visiting the different quarters of the Cassavee, and
making such inquiries and observations as were necessary for his purpose.
Hafiz accompanied him, completely satisfied with acting in obedience to
his mistress. In a short time the King had perfected the theory of a new
establishment infinitely more advantageous to the Almoçadem, and far
milder for his Christian associates: this project he delivered to Kara Aziek,
through Hafiz, who was recommended in it, to be made Governor of the
whole. Aziek studied it attentively, and assented to its excellence with all
the ardour of her benevolent nature; soon afterwards she sought and
obtained her father’s approval.
Transported with this success, she urged El Hader to send for that
enlightened Christian, who thus united regard for his interest with pity for
his own countrymen; El Hader had not forgotten their last interview, but no
longer apprehensive of seeing a madman, he yielded to his daughter’s wish.
The Almoçadem received Sebastian with his usual good-natured
indolence; and after having suggested one or two alterations, and demanded
a few explanations, he pronounced the desired acquiescence. Sebastian
would not have prostrated himself to any mortal for a favor merely selfish;
but at this mercy to so many sufferers, he cast himself at the feet of Kara
Aziek, who sat wrapt up in her veil, exclaiming in Italian.
“It is to you, amiable Lady! that the Christians owe these blessings;
henceforth I will believe myself your slave, and then bondage will be no
longer abhorrent.”
“Ah Christian!” cried the lovely Moor, and stopping abruptly, she
averted her eyes with a palpitating heart.
Sebastian knew not the soft confusion his ardent speech had caused; he
forgot the woman in Kara Aziek, and saw only the pure and disinterested
spirit of an angel.
El Hader now made some remarks upon the improvements in his
domain, which he was told were the effects of his Portuguese slave’s
exertions, adding, “Thou must surely be satisfied with the miraculous
kindness with which thou are treated, and consequently pleased with thy
situation?”
This observation afforded Sebastian the opportunity he sought. “Many
and important favors,” he said “I gratefully acknowledge in my own person,
and in that of every Christian inhabiting this place, but while I labour to
shew my sense of your indulgence by a peaceable demeanour and voluntary
acts of service, remember El Hader, that I do not conceive myself bound to
forego the hope of liberty: my heart is filled with it;—day and night my
thoughts are on it; I warn you therefore not to suppose that any thing can
make me abandon a resolution to break my bonds, if possible. You refuse a
ransom, therein you are merciless and tyrannical, and by that act free me
from the obligation honour would otherwise impose: would you accept
money as an equivalent for me (however exorbitant the sum) I would not
steal myself away, and defraud you of your rightful gain, though liberty
tempted me from a thousand avenues; now, I hold my conscience
unshackled: if I can escape, I will, but wherever I go, be assured I shall bear
with me a salutary remembrance of Moorish virtues.”
“Is not this fellow a madman?” asked El Hader, turning with a smile to
his daughter. “This confession of his may clip his wings. Christian, (he
added) dost thou not believe I can abridge thy present freedom, and so
prevent thy escape?”
“Assuredly I do, returned the impetuous monarch, but that consideration
ought not to deter me from asserting my right to use every means of
restoring myself to my country. I tell it you, that you may not hereafter call
me a base, ungrateful hypocrite; I tell it you, that you may not impute to
others my imagined guilt. God forbid that I should be the occasion of any
man’s disgrace! should I effect my purpose, recollect it will be all my own
work, and that neither your slaves nor your servants will have had the
smallest share in it.
“Rash, but amiable man!” exclaimed Kara Aziek, regarding him with a
look of admiration, “O that thou couldst forget thy country and be happy in
Africa!”
The tenderness of her tone penetrated the heart of Sebastian, he did not
reply by words, but his eloquent eyes fixed for a moment upon her, spoke
only too ardently the gratitude she inspired: again the soft bosom of Kara
Aziek palpitated with an unknown emotion, and covering her figure still
more with her veil—(as if fearing her soul was visible)—she hastily
withdrew.
El Hader detained the King a few moments longer, jesting him on his
extravagant hopes, and assuring him, that though still indulgently used, he
should be well watched. Sebastian listened in silent majesty, then quitted
him, completely satisfied with their mutual understanding.
While he returned to toil and the society of Gaspar, who was now able to
bear a moderate part in the work of the gardens, Kara Aziek retired to her
own apartments agitated with pain and pleasure: unknown to herself, the
pity with which she had at first regarded the young and handsome Christian
was now changed into a sentiment less disinterested but more animated; his
situation and character were alike interesting; his conversation insensibly
stole her from herself; and his graceful image contrasted with the swarthy
Moors and pallid slaves around, was ever present to her eyes: at the sound
of his voice or his flute, (heard at a distance from the gardens,) she would
feel her heart throb tumultuously; and when his past looks or words crossed
her memory, a delightful thrill would run through her veins.
Formerly Benevolence was content to administer to his wants and to
secure him from hardships; now Love panted to surround him with the
delicacies of refinement, and to procure for him exemption from every
occupation. She would send him the choicest fruits and viands, essences
and fragrant oils for his use after the bath, books, music, and becoming
apparel; she would watch his looks with silent anxiety, foreseeing
indisposition ere it approached him, and providing against it by medicines
prepared by her own hand; a favorite maid cautiously conveyed these things
to the apartment of Sebastian, who received them silently and distributed
them with discretion.
Though indulged in a freedom perfectly singular in Barbary, Aziek dared
not openly pour upon a Christian such a shower of benefits, she was obliged
to find frequent employment for him, that she might see and converse with
him unsuspected. At those times she would talk to him not merely of his
country but upon such subjects as enlightened her mind and displayed the
treasures of his: thus did she unconsciously weave her own chains, little
dreaming that the heart she thus learned to idolize, was the property of
another.
Wholly devoted to the remembrance of Donna Gonsalva, and too much
occupied with his various anxieties, Sebastian never once thought of the
possibility of destroying the peace of his benefactress; he beheld her with
the tenderest and most exalted admiration; and as she shewed to Gaspar
nearly equal compassion, (for Gaspar was dear to her on his account,) he
considered her as a creature formed by providence expressly for the purpose
of succouring unfortunate Christians.
The new order of things was now established throughout El Hader’s
residence, and Sebastian became painfully anxious for its success. By
adapting every occupation to the peculiar powers of each man, and allowing
them more rest and more food, he knew that nothing short of determined
industry would render their master satisfied with the change; he was
therefore obliged to urge these motives unremittingly amongst them till he
conquered their habitual languor, and made them feel that the persevering
activity of half the day would insure to them repose and comfort during the
remainder. The perfect completion of his system left him free to think solely
of his escape.
To keep his promise with El Hader, and avert destruction from Gaspar,
Sebastian refrained from telling him of his purpose: alone, and in secret, he
meditated and observed.
Though he was permitted to range through every part of the Cassavee
domain, it was enclosed by walls of great height and thickness, upon which,
at small distances, were placed sentinels day and night; the only possible
avenue appeared to be that part where a narrow river washed the eastern
wall, the sentinels there were far apart and relying on this natural barrier
watched carelessly: here Sebastian thought it practicable to cut a passage
through, and so passing from one side to the other, creep through the
underwood to the river, and swim across.
The eastern wall was not far from that angle of the building in which he
slept, and he might therefore pass and repass with less danger of discovery;
though his door was locked nightly, his window was unbarred, and from it
he could easily descend into the garden.
On reconnoitring the particular spot he pitched on, he found that a
cluster of very thick trees would conceal him from possible observation,
and that a canal, not many paces distant, would serve as a reservoir for the
rubbish and stones: inspirited by these providential circumstances he
commenced his project the ensuing night.
The implements of daily toil served now for the instruments of freedom;
Sebastian was disciplined to labour, and rendered expert by practice; every
night he worked during the half of it, leaving the increasing chasm, masked
with stones well-fitted. Success seemed to await him; no one hitherto had
suspected his nocturnal employment, and Gaspar, for whose delicate health
he feared, (as he resolved not to abandon him in a dying state,) rather
strengthened than declined. Meanwhile peace and comfort reigned
throughout the abode of El Hader; his slaves looked better, and performed
more than they had ever done; groans and sighs were no longer heard in the
Cassavee, and if the captives still wept for their country and friends, it was
in the privacy of their own chambers.
Kara Aziek continued to move amongst them like the angel of pity; she
compassionated them all, but she loved one, whose “looks were now her
soul’s food.” Sometimes she sent for him to instruct her in the Portuguese
songs and the Portuguese history, and then, though her father were present,
she would speak to him in Italian of the subject nearest his heart.
Sometimes she would loiter with her women for hours beside him in the
gardens under pretence of giving orders about her bowers and her green-
houses, when in reality it was to hear the music of his voice and to “suck in
the honey of his sweet discourse.”
Indeed Kara Aziek could no longer command, where she would
willingly have served; respect ever accompanies love; and her worth-
inspired affection now shrunk from those acts which reminded her that the
object of her devotion was in a state of humiliation.

You might also like