0% found this document useful (0 votes)
6 views82 pages

Dive Into Python A Guide To The Python Language For Programmers Pilgrim pdf download

The document provides information about the book 'Dive Into Python' by Mark Pilgrim, including various editions and related resources available for download. It outlines the contents of the book, which covers fundamental and advanced Python programming concepts. Additionally, it includes details about copyright, distribution, and the editorial team involved in the book's publication.

Uploaded by

wxbuuqz3767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views82 pages

Dive Into Python A Guide To The Python Language For Programmers Pilgrim pdf download

The document provides information about the book 'Dive Into Python' by Mark Pilgrim, including various editions and related resources available for download. It outlines the contents of the book, which covers fundamental and advanced Python programming concepts. Additionally, it includes details about copyright, distribution, and the editorial team involved in the book's publication.

Uploaded by

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

Dive Into Python A Guide To The Python Language

For Programmers Pilgrim download

https://ebookbell.com/product/dive-into-python-a-guide-to-the-
python-language-for-programmers-pilgrim-11927998

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Dive Into Python 3 Mark Pilgrim

https://ebookbell.com/product/dive-into-python-3-mark-pilgrim-2525732

Dive Into Python Mark Pilgrim

https://ebookbell.com/product/dive-into-python-mark-pilgrim-32704064

Dive Into Python Pilgrim Mark

https://ebookbell.com/product/dive-into-python-pilgrim-mark-55668124

Dive Into Python 3 2nd Edition Mark Pilgram

https://ebookbell.com/product/dive-into-python-3-2nd-edition-mark-
pilgram-7141068
Dive Into Python Mark Pilgrim

https://ebookbell.com/product/dive-into-python-mark-pilgrim-43186686

Dive Into Python 3 Mark Pilgrim

https://ebookbell.com/product/dive-into-python-3-mark-pilgrim-2463166

Dive Into Python Mark Pilgrim

https://ebookbell.com/product/dive-into-python-mark-pilgrim-43033722

Dive Into Python 3 Mark Pilgrim

https://ebookbell.com/product/dive-into-python-3-mark-pilgrim-5412084

Dive Into Data Science Use Python To Tackle Your Toughest Business
Challenges 1st Edition Bradford Tuckfield

https://ebookbell.com/product/dive-into-data-science-use-python-to-
tackle-your-toughest-business-challenges-1st-edition-bradford-
tuckfield-48471960
Dive Into Python 3

■■■

Mark Pilgrim

i
Dive Into Python 3
Copyright © 2009 by Mark Pilgrim
All rights reserved. No part of this work may be reproduced or transmitted in any form or by
any means, electronic or mechanical, including photocopying, recording, or by any
information storage or retrieval system, without the prior written permission of the copyright
owner and the publisher.
ISBN-13 (pbk): 978-1-4302-2415-0
ISBN-13 (electronic): 978-1-4302-2416-7
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
Lead Editor: Duncan Parkes
Technical Reviewer: Simon Willison
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony
Campbell, Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie,
Jeffrey Pepper, Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade,
Tom Welsh
Project Managers: Richard Dal Porto and Debra Kelly
Copy Editors: Nancy Sixsmith, Heather Lang, Patrick Meader, and Sharon Terdeman
Compositor: folio 2
Indexer: Julie Grady
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-
[email protected], or visit http://www.springeronline.com.
For information on translations, please e-mail [email protected], or visit
http://www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or
promotional use. eBook versions and licenses are also available for most titles. For more
information, reference our Special Bulk Sales–eBook Licensing web page at
http://www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although
every precaution has been taken in the preparation of this work, neither the author(s) nor
Apress shall have any liability to any person or entity with respect to any loss or damage
caused or alleged to be caused directly or indirectly by the information contained in this work.

ii
For Michael

iii
Contents at a Glance

■Foreword........................................................................................................................... xiii
■About the Author ................................................................................................................ xv
■About the Technical Reviewer........................................................................................... xvi
■Acknowledgments............................................................................................................ xvii
■Installing Python ............................................................................................................. xviii
■Chapter 1: Your First Python Program ................................................................................. 1
■Chapter 2: Native Datatypes............................................................................................... 15
■Chapter 3: Comprehensions ............................................................................................... 43
■Chapter 4: Strings .............................................................................................................. 53
■Chapter 5: Regular Expressions ......................................................................................... 69
■Chapter 6: Closures and Generators................................................................................... 87
■Chapter 7: Classes and Iterators ...................................................................................... 101
■Chapter 8: Advanced Iterators ......................................................................................... 113
■Chapter 9: Unit Testing..................................................................................................... 131
■Chapter 10: Refactoring ................................................................................................... 155
■Chapter 11: Files .............................................................................................................. 167
■Chapter 12: XML............................................................................................................... 185
■Chapter 13: Serializing Python Objects ............................................................................ 205
■Chapter 14: HTTP Web Services ....................................................................................... 225
■Chapter 15: Case Study: Porting chardet to Python 3 ...................................................... 253
■Chapter 16: Packaging Python Libraries.......................................................................... 279
■Appendix A: Porting Code to Python 3 with 2to3 ............................................................. 295
■Appendix B: Special Method Names................................................................................. 327
■Appendix C: Where to Go From Here................................................................................. 345
■Index ................................................................................................................................ 347

iv
Contents

■Foreword........................................................................................................................... xiii
■About the Author ................................................................................................................ xv
■About the Technical Reviewer........................................................................................... xvi
■Acknowledgments............................................................................................................ xvii
■Installing Python ............................................................................................................. xviii
Which Python Is Right for You? ...............................................................................................................xi
Installing on Microsoft Windows........................................................................................................... xii
Installing on Mac OS X ...........................................................................................................................xxi
Installing on Ubuntu Linux................................................................................................................xxxiii
Installing on Other Platforms ................................................................................................................ xli
Using the Python Shell ........................................................................................................................... xli
Python Editors and IDEs .......................................................................................................................xliv
■Chapter 1: Your First Python Program ................................................................................. 1
Declaring Functions ..................................................................................................................................2
Optional and Named Arguments..............................................................................................................3
Writing Readable Code..............................................................................................................................5
Documentation Strings .............................................................................................................................5
The import Search Path.............................................................................................................................6
Everything Is an Object .............................................................................................................................7
What’s an Object? ......................................................................................................................................8
Indenting Code ..........................................................................................................................................8
Exceptions ..................................................................................................................................................9
Catching Import Errors ...........................................................................................................................11
Unbound Variables..................................................................................................................................12
Running Scripts .......................................................................................................................................12
Further Reading Online...........................................................................................................................13

v
■ CONTENTS

■Chapter 2: Native Datatypes............................................................................................... 15


Booleans ...................................................................................................................................................15
Numbers ...................................................................................................................................................16
Coercing Integers to Floats and Vice Versa ............................................................................................17
Common Numerical Operations .......................................................................................................18
Fractions...................................................................................................................................................19
Trigonometry ...........................................................................................................................................20
Numbers in a Boolean Context ...............................................................................................................20
Lists...........................................................................................................................................................21
Creating a List .....................................................................................................................................21
Slicing a List ........................................................................................................................................22
Adding Items to a List .........................................................................................................................23
Searching For Values in a List ............................................................................................................25
Removing Items from a List ...............................................................................................................26
Removing Items from a List: Bonus Round ......................................................................................26
Lists in a Boolean Context ..................................................................................................................27
Tuples .......................................................................................................................................................28
Tuples in a Boolean Context ..............................................................................................................30
Assigning Multiple Values at Once.....................................................................................................30
Sets............................................................................................................................................................31
Modifying a Set ...................................................................................................................................33
Removing Items from a Set ................................................................................................................34
Common Set Operations ....................................................................................................................35
Sets in a Boolean Context ...................................................................................................................37
Dictionaries..............................................................................................................................................38
Creating a Dictionary .........................................................................................................................38
Modifying a Dictionary.......................................................................................................................38
Mixed-Value Dictionaries...................................................................................................................39
Dictionaries in a Boolean Context .....................................................................................................40
None..........................................................................................................................................................41
None in a Boolean Context.................................................................................................................41
Further Reading Online...........................................................................................................................42
■Chapter 3: Comprehensions ............................................................................................... 43
Working With Files and Directories........................................................................................................43
The Current Working Directory .........................................................................................................43
Working with Filenames and Directory Names ................................................................................44
Listing Directories...............................................................................................................................46
Getting File Metadata .........................................................................................................................47
Constructing Absolute Pathnames ....................................................................................................47
List Comprehensions...............................................................................................................................48
Dictionary Comprehensions...................................................................................................................50

vi
■ CONTENTS

Fun with Dictionary Comprehensions ..............................................................................................51


Set Comprehensions ...............................................................................................................................51
Further Reading Online...........................................................................................................................52
■Chapter 4: Strings .............................................................................................................. 53
Unicode ....................................................................................................................................................54
Diving In...................................................................................................................................................56
Formatting Strings...................................................................................................................................56
Compound Field Names..........................................................................................................................57
Format Specifiers.....................................................................................................................................59
Other Common String Methods .............................................................................................................60
Slicing a String .........................................................................................................................................61
Strings versus Bytes .................................................................................................................................62
Character Encoding of Python Source Code..........................................................................................65
Further Reading Online...........................................................................................................................66
■Chapter 5: Regular Expressions ......................................................................................... 69
Case Study: Street Addresses ..................................................................................................................69
Case Study: Roman Numerals ................................................................................................................71
Checking for Thousands .........................................................................................................................72
Checking for Hundreds ...........................................................................................................................73
Using the {n,m} Syntax ............................................................................................................................75
Checking for Tens and Ones ...................................................................................................................76
Verbose Regular Expressions ..................................................................................................................78
Case Study: Parsing Phone Numbers .....................................................................................................80
Further Reading Online...........................................................................................................................85
■Chapter 6: Closures and Generators................................................................................... 87
I Know, Let’s Use Regular Expressions!..................................................................................................88
A List of Functions ...................................................................................................................................90
A List of Patterns ......................................................................................................................................92
A File of Patterns ......................................................................................................................................95
Generators................................................................................................................................................96
A Fibonacci Generator.............................................................................................................................98
A Plural Rule Generator...........................................................................................................................99
Further Reading Online.........................................................................................................................100
■Chapter 7: Classes and Iterators ...................................................................................... 101
Defining Classes.....................................................................................................................................102
The __init__() Method............................................................................................................................102
Instantiating Classes .............................................................................................................................103
Instance Variables .................................................................................................................................104
A Fibonacci Iterator ...............................................................................................................................105
A Plural Rule Iterator.............................................................................................................................107
Further Reading Online.........................................................................................................................112

vii
■ CONTENTS

■Chapter 8: Advanced Iterators ......................................................................................... 113


Finding All Occurrences of a Pattern....................................................................................................115
Finding the Unique Items in a Sequence .............................................................................................115
Making Assertions .................................................................................................................................117
Generator Expressions ..........................................................................................................................117
Calculating Permutations … the Lazy Way..........................................................................................119
Other Fun Stuff in the itertools Module ...............................................................................................120
A New Kind of String Manipulation......................................................................................................124
Evaluating Arbitrary Strings as Python Expressions ...........................................................................126
Putting It All Together ...........................................................................................................................130
Further Reading Online.........................................................................................................................130
■Chapter 9: Unit Testing..................................................................................................... 131
A Single Question...................................................................................................................................132
Halt and Catch Fire................................................................................................................................138
More Halting, More Fire ........................................................................................................................141
And One More Thing … .........................................................................................................................144
A Pleasing Symmetry.............................................................................................................................146
More Bad Input ......................................................................................................................................150
■Chapter 10: Refactoring ................................................................................................... 155
Handling Changing Requirements.......................................................................................................158
Refactoring.............................................................................................................................................162
Further Reading Online.........................................................................................................................166
■Chapter 11: Files .............................................................................................................. 167
Reading from Text Files.........................................................................................................................167
Character Encoding Rears Its Ugly Head ........................................................................................168
Stream Objects ..................................................................................................................................169
Reading Data from a Text File..........................................................................................................170
Closing Files ......................................................................................................................................172
Closing Files Automatically..............................................................................................................173
Reading Data One Line at a Time.....................................................................................................173
Writing to Text Files...............................................................................................................................175
Character Encoding Again ...............................................................................................................176
Binary Files.............................................................................................................................................177
Streams Objects from Nonfile Sources.................................................................................................178
Handling Compressed Files .............................................................................................................179
Standard Input, Output, and Error.......................................................................................................180
Redirecting Standard Output...........................................................................................................181
Further Reading Online.........................................................................................................................184
■Chapter 12: XML............................................................................................................... 185
A 5-Minute Crash Course in XML .........................................................................................................186

viii
■ CONTENTS

The Structure of an Atom Feed .............................................................................................................189


Parsing XML ...........................................................................................................................................191
Elements Are Lists..................................................................................................................................192
Attributes Are Dictionaries....................................................................................................................193
Searching for Nodes Within an XML Document..................................................................................194
Going Further with lxml ........................................................................................................................197
Generating XML .....................................................................................................................................199
Parsing Broken XML ..............................................................................................................................202
Further Reading Online.........................................................................................................................204
■Chapter 13: Serializing Python Objects ............................................................................ 205
A Quick Note About the Examples in this Chapter .........................................................................205
Saving Data to a Pickle File ...................................................................................................................206
Loading Data from a Pickle File............................................................................................................208
Pickling Without a File ..........................................................................................................................209
Bytes and Strings Rear Their Ugly Heads Again ..................................................................................210
Debugging Pickle Files ..........................................................................................................................210
Serializing Python Objects to be Read by Other Languages ...............................................................213
Saving Data to a JSON File ....................................................................................................................213
Mapping Python Datatypes to JSON ....................................................................................................215
Serializing Datatypes Unsupported by JSON.......................................................................................215
Loading Data from a JSON File .............................................................................................................220
Further Reading Online.........................................................................................................................222
■Chapter 14: HTTP Web Services ....................................................................................... 225
Features of HTTP ...................................................................................................................................226
Caching..............................................................................................................................................226
Last-Modified Checking ...................................................................................................................227
ETags..................................................................................................................................................228
Compression .....................................................................................................................................229
Redirects............................................................................................................................................229
How Not to Fetch Data Over HTTP.......................................................................................................230
What’s On the Wire?...............................................................................................................................231
Introducing httplib2 ..............................................................................................................................234
Caching with httplib2 .......................................................................................................................237
Handling Last-Modified and ETag Headers with httplib2 .............................................................240
Handling Compression with httplib2..............................................................................................242
Handling Redirects with httplib2 ....................................................................................................243
Beyond HTTP GET .................................................................................................................................246
Beyond HTTP POST...............................................................................................................................250
Further Reading Online.........................................................................................................................252
■Chapter 15: Case Study: Porting chardet to Python 3 ...................................................... 253
What Is Character Encoding Auto-Detection? .....................................................................................253

ix
■ CONTENTS

Why Auto-Detection Is Difficult.......................................................................................................253


Auto-Encoding Algorithms...............................................................................................................254
Introducing the chardet Module ..........................................................................................................254
UTF-n with a BOM ............................................................................................................................254
Escaped Encodings ...........................................................................................................................254
Multibyte Encodings.........................................................................................................................255
Single-Byte Encodings......................................................................................................................255
windows-1252 ...................................................................................................................................256
Running 2to3..........................................................................................................................................256
A Short Digression Into Multi-File Modules ........................................................................................259
Fixing What 2to3 Can’t ..........................................................................................................................261
False Is Invalid Syntax ......................................................................................................................261
No Module Named Constants ..........................................................................................................262
Name 'file' Is Not Defined.................................................................................................................263
Can’t Use a String Pattern on a Bytes-Like Object..........................................................................264
Can’t Convert 'bytes' Object to str Implicitly ..................................................................................266
Unsupported Operand type(s) for +: 'int' and 'bytes' .....................................................................269
ord() Expected String of Length 1, but int Found ...........................................................................270
Unorderable Types: int() >= str() .....................................................................................................273
Global Name 'reduce' Is not Defined...............................................................................................275
Lessons Learned.....................................................................................................................................277
■Chapter 16: Packaging Python Libraries.......................................................................... 279
Things Distutils Can’t Do for You .........................................................................................................280
Directory Structure................................................................................................................................281
Writing Your Setup Script.................................................................................................................282
Classifying Your Package ......................................................................................................................284
Examples of Good Package Classifiers ............................................................................................284
Checking Your Setup Script for Errors .................................................................................................287
Creating a Source Distribution .............................................................................................................287
Creating a Graphical Installer...............................................................................................................289
Building Installable Packages for Other Operating Systems .........................................................290
Adding Your Software to the Python Package Index ...........................................................................291
The Many Possible Futures of Python Packaging................................................................................292
Further Reading Online.........................................................................................................................293
■Appendix A: Porting Code to Python 3 with 2to3 ............................................................. 295
print Statement......................................................................................................................................295
Unicode String Literals..........................................................................................................................296
unicode() Global Function ....................................................................................................................296
long Datatype.........................................................................................................................................297
<> Comparison ......................................................................................................................................297
has_key() Dictionary Method................................................................................................................298

x
■ CONTENTS

Dictionary Methods that Return Lists ..................................................................................................299


Renamed or Reorganized Modules.......................................................................................................299
http.....................................................................................................................................................300
urllib ..................................................................................................................................................300
dbm....................................................................................................................................................301
xmlrpc................................................................................................................................................302
Other Modules ..................................................................................................................................302
Relative Imports Within a Package.......................................................................................................304
next() Iterator Method...........................................................................................................................305
filter() Global Function..........................................................................................................................306
map() Global Function ..........................................................................................................................306
reduce() Global Function ......................................................................................................................307
apply() Global Function ........................................................................................................................308
intern() Global Function .......................................................................................................................308
exec Statement.......................................................................................................................................309
execfile Statement .................................................................................................................................309
repr Literals (Backticks) ........................................................................................................................310
try...except Statement............................................................................................................................310
raise Statement ......................................................................................................................................312
throw Method on Generators................................................................................................................312
xrange() Global Function ......................................................................................................................313
raw_input() and input() Global Functions...........................................................................................314
func_* Function Attributes....................................................................................................................314
xreadlines() I/O Method ........................................................................................................................315
lambda Functions that Take a Tuple Instead of Multiple Parameters...............................................316
Special Method Attributes.....................................................................................................................317
__nonzero__ Special Method ................................................................................................................317
Octal Literals ..........................................................................................................................................318
sys.maxint ..............................................................................................................................................318
callable() Global Function.....................................................................................................................319
zip() Global Function.............................................................................................................................319
StandardError Exception ......................................................................................................................319
types Module Constants ........................................................................................................................320
isinstance() Global Function.................................................................................................................321
basestring Datatype...............................................................................................................................321
itertools Module.....................................................................................................................................322
sys.exc_type, sys.exc_value, sys.exc_traceback ...................................................................................322
List Comprehensions Over Tuples........................................................................................................323
os.getcwdu() Function...........................................................................................................................323
Metaclasses ............................................................................................................................................323
Matters of Style ......................................................................................................................................324
set() Literals (Explicit).......................................................................................................................324

xi
■ CONTENTS

buffer() Global Function (Explicit) ..................................................................................................324


Whitespace Around Commas (Explicit) ..........................................................................................325
Common Idioms (Explicit)...............................................................................................................325
■Appendix B: Special Method Names................................................................................. 327
Basics ......................................................................................................................................................327
Classes that Act Like Iterators ...............................................................................................................328
Computed Attributes .............................................................................................................................328
Classes that Act Like Functions.............................................................................................................331
Classes that Act Like Sequences............................................................................................................332
Classes that Act Like Dictionaries.........................................................................................................334
Classes that Act Like Numbers..............................................................................................................335
Classes that Can Be Compared .............................................................................................................339
Classes that Can Be Serialized ..............................................................................................................340
Classes that Can Be Used in a “with” Block .........................................................................................340
Really Esoteric Stuff...............................................................................................................................342
Further Reading Online.........................................................................................................................343
■Appendix C: Where to Go From Here................................................................................. 345
■Index ................................................................................................................................ 347

xii
Foreword

Seven years ago, I’d have looked at you incredulously and probably laughed if you had told me I would
be sitting here today writing the foreword to a book, much less the foreword to a programming book. Yet
here I am.
Seven years ago, I was just a test engineer with some scripting skills and a systems administration
background. I had little programming experience and even less passion for it.
One day, a soon-to-be-coworker of mine mentioned this “new” scripting language called Python.
He said it was easy to learn and might add to my skill set. I was wary because programmers seemed to be
so separated from my “real world” of tests and systems and users. But his description also made me
curious, so I visited the nearest bookstore and bought the first book on the subject I found.
The book I bought was the original Dive Into Python, by Mark Pilgrim. I have to believe that I am not
the only person who can say, without exaggeration, that Mark’s book changed my life and career forever.
The combination of Mark’s book, his passion for Python, his presentation of the material, and even
the Python (the language itself) fundamentally altered the way I thought. The combination drove me not
just to read “yet another book about tech stuff”; it drove me to code, to represent my ideas in a
completely new and exciting way. Mark’s passion for the language inspired me with a newfound
passion.
Now, seven years later, I’m a contributor to the Python standard library–an active community
member–and I teach the language to as many people as I can. I use it in my free time, I use it at my job,
and I contribute to it in between my daughter’s naps. Dive Into Python–and Python itself–changed me.
Python is neither the prettiest nor most flexible language out there. But it is clean, simple, and
powerful. Its elegance lies in its simplicity and its practicality. Its flexibility enables you (or anyone) to
get something–anything–done simply by “keeping out of your way.”
I've said for some time the beauty of Python is that it scales “up.” It is useful for someone who wants
only to do some math or write a simple script. And it is equally useful for programmers who want to
create large-scale systems, web frameworks, and multimillion dollar video-sharing sites.
Python has not been without its warts, though. Building a language is, at least in my mind, much
like learning to program. It’s an evolutionary process where you constantly have to question the
decisions you’ve made and be willing to correct those decisions.
Python 3 admits to some of those mistakes with its new fixes, removing some of the old warts, while
also possibly introducing some new ones. Python 3 shows a self-awareness and willingness to evolve in
much-needed ways you don't see in a lot of things.
Python 3 does not redefine, fundamentally alter, or suddenly invalidate all the Python you knew
before. Rather, it takes something that is time-proven and battle-worn and improves on it in rational,
practical ways.

xiii
■ FOREWORD

Python 3 doesn’t represent the end of the evolution of the language. New features, syntax, and
libraries continue to be added; and it will probably be added, tweaked, and removed for as long as
Python carries on.
Python 3 is simply a cleaner, more evolved platform for you, the reader, to get things done with.
Like Python 3, Dive Into Python 3 represents the evolution of something that was already very good
becoming something even better. Mark’s passion, wit, and engaging style are still there; and the material
has been expanded, improved, and updated. But like Python 3 itself, version 3 of this series
fundamentally remains the thing that originally gave me such a passion for programming.
Python’s simplicity is infectious. The passion of its community, not to mention the passion with
which the language is created and maintained, remains astounding.
I hope Mark’s passion, and Python itself, inspires you as it did me seven years ago. I hope you find
Python, and Python 3, to be as practical and powerful as the hundreds of thousands of programmers and
companies that use it across the world.
Jesse Noller
Python Developer

xiv
About the Author

■By day, Mark Pilgrim is a developer advocate for open source and open
standards. By night, he is a husband and father who lives in North Carolina with
his wife, his two sons, and his big, slobbery dog. He spends his copious free time
sunbathing, skydiving, and making up autobiographical information.

xv
■ FOREWORD

About the Technical Reviewer

■Simon Willison is a speaker, writer, developer and all-around web technology


enthusiast. Simon works for Guardian News and Media as a technical architect for
both guardian.co.uk and the recently launched Guardian Developer Network.
Before joining the Guardian Simon worked as a consultant for clients that
included the BBC, Automattic, and GCap Media. He is a past member of Yahoo!'s
Technology Development team (his projects included the initial prototype of
FireEagle, Yahoo!'s location broker API). Prior to Yahoo!, he worked at the
Lawrence Journal-World, an award winning local newspaper in Kansas.
Simon is a co-creator of the Django web framework, and a passionate
advocate for Open Source and standards-based development. He maintains a
popular web development weblog at http://simonwillison.net.

xvi
Acknowledgments

The author would like to thank his wife for her never-ending support and encouragement, without
which this book would still be an item on an ever-growing wish list.
Thank you to Raymond Hettinger for relicensing his alphametics solver so I could use it as the basis
for Chapter 8.
Thank you to Jesse Noller for patiently explaining so many things to me at PyCon 2009, so that I
could explain them to everyone else.
Finally, thank you to the many people who gave me feedback during the public writing process,
especially Giulio Piancastelli, Florian Wollenschein, and all the good people of python.reddit.com.

xvii
■ FOREWORD

Installing Python

Welcome to Python 3. Let’s dive in. In this chapter, you’ll install the version of Python 3 that’s right
for you.

Which Python Is Right for You?


The first thing you need to do with Python is install it. Or do you?
If you’re using an account on a hosted server, your Internet service provider (ISP) might have
already installed Python 3. If you’re running Linux at home, you might already have Python 3, too. Most
popular GNU/Linux distributions come with Python 2 in the default installation; a small but growing
number of distributions also include Python 3. (As you’ll see in this chapter, you can have more than one
version of Python installed on your computer.) Mac OS X includes a command-line version of Python 2,
but (as of this writing) it does not include Python 3. Microsoft Windows does not come with any version
of Python. But don’t despair! You can point and click your way through installing Python, regardless of
which operating system you have.
The easiest way to check for Python 3 on your Linux or Mac OS X system is to get to a command line.
On Linux, look in your Applications menu for a program called Terminal. (It might be in a submenu such
as Accessories or System.) On Mac OS X, there is an application called Terminal.app in your
/Application/Utilities/ folder.
Once you’re at a command-line prompt, just type python3 (all lowercase, no spaces) and see what
happens. On my home Linux system, Python 3 is already installed, and this command gets me into the
Python interactive shell, as shown in Listing 0-1.

Listing 0-1. Python Interactive Shell

mark@atlantis:~$ python3
Python 3.0.1+ (r301:69556, Apr 15 2009, 17:25:52)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Type exit() and press Enter to exit the Python interactive shell.
My web hosting provider also runs Linux and provides command-line access, but as Listing 0-2
shows, my server does not have Python 3 installed. (Boo!)

xviii
■ INSTALLING PYTHON

Listing 0-2. Python Interactive Shell

mark@manganese:~$ python3
bash: python3: command not found

So back to the question that started this section: “Which Python is right for you?” The answer is
simple: whichever one runs on the computer you already have.

Installing on Microsoft Windows


Windows comes in two architectures these days: 32-bit and 64-bit. Of course, there are lots of different
versions of Windows!XP, Vista, and Windows 7!but Python runs on all of them. The more important
distinction is 32-bit versus 64-bit. If you have no idea what architecture you’re running, it’s probably
32-bit.
Visit http://python.org/download/ and download the appropriate Python 3 Windows installer for
your architecture. Your choices will look something like these:
• Python 3.1 Windows installer (Windows binary!does not include source)
• Python 3.1 Windows AMD64 installer (Windows AMD64 binary!does not include
source)
I don’t want to include direct download links here because minor updates of Python happen all the
time and I don’t want to be responsible for you missing important updates. You should always install the
most recent version of Python 3.x unless you have some esoteric reason not to.
Once your download is complete, double-click the .msi file. Windows will display a security alert
because you’re about to be running executable code. The official Python installer is digitally signed by
the Python Software Foundation, the nonprofit corporation that oversees Python development. Don’t
accept imitations!

xix
■ INSTALLING PYTHON

Click the Run button to launch the Python 3 installer.

The first question the installer will ask you is whether you want to install Python 3 for all users or just for
you. The default choice is “Install for all users,” which is the best choice unless you have a good reason to
choose otherwise. (One reason why you might want to choose “Install just for me” is that you are
installing Python on your company’s computer and you don’t have administrative rights on your
Windows account. But then why are you installing Python without permission from your company’s
Windows administrator? Don’t get me in trouble here!)

xx
■ INSTALLING PYTHON

Click the Next button to accept your choice of installation type.

Next, the installer will prompt you to choose a destination directory. The default for all versions of
Python 3.1.x is C:\Python31\, which should work well for most users unless you have a specific reason to
change it. If you maintain a separate drive letter for installing applications, you can browse to it using
the embedded controls or simply type the pathname in the box below. You are not limited to installing
Python on the C: drive; you can install it on any drive, in any folder.

xxi
■ INSTALLING PYTHON

Click the Next button to accept your choice of destination directory.

Although the next page looks complicated, it’s not really difficult. Like many installers, you have the
option not to install every single component of Python 3. If disk space is especially tight, you can exclude
certain components.
• Register Extensions allows you to double-click Python scripts (.py files) and run
them (recommended but not required). This option doesn’t require any disk
space, so there is little point in excluding it.
• Tcl/Tk is the graphics library used by the Python shell, which you will use
throughout this book. I strongly recommend keeping this option.
• Documentation installs a help file that contains much of the information on
http://docs.python.org. This option is recommended if you are on dialup or have
limited Internet access.
• Utility Scripts includes the 2to3.py script, which you’ll learn about later in this
book. It is required if you want to learn about migrating existing Python 2 code to
Python 3. If you have no existing Python 2 code, you can skip this option.
• Test suite is a collection of scripts used to test the Python interpreter. You will not
use it in this book, nor have I ever used it in the course of programming in Python.
Completely optional.

xxii
■ INSTALLING PYTHON

If you don’t know how much disk space you have, click the Disk Usage button. The installer will list
your drive letters, compute how much space is available on each drive, and calculate how much would
be left after installation.

xxiii
■ INSTALLING PYTHON

Click the OK button to return to the customization page. If you decide to exclude an option, select
the drop-down button before the option and select “Entire feature will be unavailable”. For example,
excluding the Test suite will save you a whopping 7908KB of disk space.

xxiv
■ INSTALLING PYTHON

Click the Next button to accept your choice of options.

xxv
■ INSTALLING PYTHON

The installer will copy all the necessary files to your chosen destination directory. (This happens so
quickly, I had to try it three times to even get a screenshot of it!)

xxvi
■ INSTALLING PYTHON

Click the Finish button to exit the installer.

xxvii
■ INSTALLING PYTHON

In your Start menu, there should be a new item called Python 3.1, in which you find a program
called IDLE. Select this item to run the interactive Python shell.

Installing on Mac OS X
All modern Macintosh computers use the Intel chip (as most Windows PCs do). Older Macs used
PowerPC chips. You don’t need to understand the difference because there’s just one Mac Python
installer for all Macs.
Visit http://python.org/download/ and download the Mac installer. It will be called something like
Python 3.1 Mac Installer Disk Image, although the version number might vary. Be sure to download
version 3.x, not 2.x.
Your browser should automatically mount the disk image and open a Finder window to show you
the contents. (If this doesn’t happen, you’ll need to find the disk image in your Downloads folder and
double-click to mount it. It will be named something like python-3.1.dmg.) The disk image contains a
number of text files (Build.txt, License.txt, ReadMe.txt) and the actual installer package, Python.mpkg.

xxviii
■ INSTALLING PYTHON

Double-click the Python.mpkg installer package to launch the Mac Python installer.

The first page of the installer gives a brief description of Python itself. It then refers you to the
ReadMe.txt file (which you didn’t read, did you?) for more details.

xxix
■ INSTALLING PYTHON

Click the Continue button to move along.

The next page actually contains some important information: Python requires Mac OS X 10.3 or
later. If you are still running Mac OS X 10.2, you should upgrade. Apple no longer provides security
updates for your operating system, and your computer is probably at risk if you ever go online. Also, you
can’t run Python 3.

xxx
■ INSTALLING PYTHON

Click the Continue button to advance.

Like all good installers, the Python installer displays the software license agreement. Python is open
source and its license is approved by the Open Source Initiative. Python has had a number of owners
and sponsors throughout its history, each of which has left its mark on the software license. But the end
result is this: Python is open source, and you are allowed use it on any platform, for any purpose,
without fee or obligation of reciprocity.

xxxi
■ INSTALLING PYTHON

Click the Continue button once again.

Because of quirks in the standard Apple installer framework, you must “agree” to the software
license to complete the installation. Because Python is open source, you are really “agreeing” that the
license is granting you additional rights instead of taking them away.

xxxii
■ INSTALLING PYTHON

Click the Agree button to continue.

The next screen allows you to change your install location. You must install Python on your boot
drive, but because of limitations of the installer, it does not enforce it. In truth, I have never had the need
to change the install location.

xxxiii
■ INSTALLING PYTHON

From this screen, you can also customize the installation to exclude certain features. If you want to
do this, click the Customize button; otherwise click the Install button.

If you choose Custom Install, the installer will present you with the following list of features:
• Python Framework is the guts of Python, and it is both selected and disabled
because it must be installed.
• GUI Applications includes IDLE, the graphical Python shell that you will use
throughout this book. I strongly recommend keeping this option selected.
• “UNIX command-line tools” includes the command-line python3 application. I
strongly recommend keeping this option, too.
• Python Documentation contains much of the information on
http://docs.python.org. This option is recommended if you are on dialup or have
limited Internet access.
• “Shell profile updater” controls whether to update your shell profile (used in
Terminal.app) to ensure that this version of Python is on the search path of your
shell. You probably don’t need to change it.

xxxiv
■ INSTALLING PYTHON

• “Fix system Python” should not be changed. It tells your Mac to use Python 3 as
the default Python for all scripts, including built-in system scripts from Apple.
This would be very bad because most of those scripts are written for Python 2, and
they would fail to run properly under Python 3.
Click the Install button to continue.

Because it installs system-wide frameworks and binaries in /usr/local/bin/, the installer will ask
you for an administrative password. There is no way to install Mac Python without administrator
privileges.

xxxv
■ INSTALLING PYTHON

After supplying the password, click the OK button to begin the installation.

xxxvi
■ INSTALLING PYTHON

The installer will display a progress meter while it installs the features you’ve selected.

Assuming that all went well, the installer will show you a big green check mark to tell you that the
installation completed successfully.

xxxvii
■ INSTALLING PYTHON

Click the Close button to exit the installer.

Assuming that you didn’t change the install location, you can find the newly installed files in the
Python 3.1 folder within your /Applications folder. The most important piece is IDLE, the graphical
Python shell.

xxxviii
■ INSTALLING PYTHON

Double-click IDLE to launch the graphical Python shell.

xxxix
■ INSTALLING PYTHON

The Python shell is where you will spend most of your time exploring Python. Examples throughout
this book will assume that you can find your way into the Python shell.

Installing on Ubuntu Linux


Modern Linux distributions are backed by vast repositories of precompiled applications, ready to install.
The exact details vary by distribution. In Ubuntu Linux, the easiest way to install Python 3 is through the
Add/Remove application in your Applications menu.
When you first launch the Add/Remove application, it will show you a list of preselected applications
in different categories. Some are already installed; most are not. Because the repository contains more
than 10,000 applications, there are different filters you can apply to see small parts of the repository. The
default filter (“Canonical-maintained applications”) is a small subset of the total number of applications
that are officially supported by Canonical, the company that creates and maintains Ubuntu Linux.

xl
■ INSTALLING PYTHON

Python 3 is not maintained by Canonical, so the first step is to drop down this filter menu and select
“All Open Source applications”.

Once you’ve widened the filter to include all open source applications, use the Search box
immediately after the filter menu to search for Python 3.

xli
■ INSTALLING PYTHON

xlii
■ INSTALLING PYTHON

Now the list of applications narrows to just those matching Python 3. You’ll check two packages.
The first is Python (v3.0), which contains the Python interpreter.

The second package you want is immediately above: IDLE (using Python-3.0). This is a graphical
Python shell that you will use throughout this book.

xliii
■ INSTALLING PYTHON

After you’ve checked those two packages, click the Apply Changes button to continue.

The package manager will ask you to confirm that you want to add both IDLE (using Python-3.0) and
Python (v3.0).

xliv
■ INSTALLING PYTHON

Click the Apply button to continue.

The package manager will show you a progress meter while it downloads the necessary packages
from Canonical’s Internet repository.

xlv
■ INSTALLING PYTHON

Once the packages are downloaded, the package manager will automatically begin installing them.

If all went well, the package manager will confirm that both packages were successfully installed.
From here, you can double-click IDLE to launch the Python shell or click the Close button to exit the
package manager.
You can always relaunch the Python shell by going to your Applications menu, choosing the
Programming submenu, and selecting IDLE.

The Python shell is where you will spend most of your time exploring Python. Examples throughout
this book will assume that you can find your way into the Python shell.

xlvi
■ INSTALLING PYTHON

Installing on Other Platforms


Python 3 is available on a number of different platforms. In particular, it is available in virtually every
Linux-, BSD-, and Solaris-based distribution. For example, RedHat Linux uses the yum package manager;
FreeBSD has its ports and packages collection; Solaris has pkgadd and friends. A quick web search for
“Python 3” + “your operating system” will tell you whether a Python 3 package is available and how to
install it.

Using the Python Shell


The Python shell is where you can explore Python syntax, get interactive help for commands, and debug
short programs. The graphical Python shell (named IDLE) also contains a decent text editor that
supports Python syntax coloring and integrates with the Python shell. If you don’t already have a favorite
text editor, you should give IDLE a try.
First things first. The Python shell itself is an amazing interactive playground. Throughout this book,
you’ll see examples like the one shown in Listing 0-3.

Listing 0-3. Evaluating Expressions in the Python Interactive Shell

>>> 1 + 1
2

The three angle brackets, >>>, denote the Python shell prompt. Don’t type that part. That’s just to let
you know that this example is meant to be followed in the Python shell.
1 + 1 is the part you type. You can type any valid Python expression or command in the Python
shell. Don’t be shy; it won’t bite! The worst that will happen is you’ll get an error message. Commands

xlvii
■ INSTALLING PYTHON

get executed immediately (after you press Enter), expressions get evaluated immediately, and the
Python shell prints out the result.
2 is the result of evaluating this expression. As it happens, 1 + 1 is a valid Python expression. The
result, of course, is 2.
Let’s try another one (see Listing 0-4).

Listing 0-4. Hello World!

>>> print('Hello world!')


Hello world!

Pretty simple, no? But there are more things you can do in the Python shell. If you ever get
stuck!you can’t remember a command or you can’t remember the proper arguments to pass a certain
function!you can get interactive help in the Python shell. Just type help() and press Enter, as shown in
Listing 0-5.

Listing 0-5. Help?

>>> help
Type help() for interactive help, or help(object) for help about object.

There are two modes of help. You can get help about a single object, which just prints out the
documentation and returns you to the Python shell prompt. You can also enter help mode, where
instead of evaluating Python expressions, you just type keywords or command names and it will print
out whatever it knows about that command.
To enter the interactive help mode, type help() and press Enter, as shown in Listing 0-6.

Listing 0-6. Interactive Help Mode

>>> help()
Welcome to Python 3.1! This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",


"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>

Note that the prompt changes from >>> to help>. This reminds you that you’re in the interactive
help mode. Now you can enter any keyword, command, module name, function name!pretty much
anything Python understands!and read documentation on it (see Listing 0-7).

xlviii
■ INSTALLING PYTHON

Listing 0-7. Interactive Help Mode

help> print (1)


Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.

help> PapayaWhip (2)


no Python documentation found for 'PapayaWhip'

help> quit (3)

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>> (4)

The following notes refer to the numbered lines in Listing 0-7:


1. To get documentation on the print() function, just type print and press Enter.
The interactive help mode will display something akin to a man page: the
function name, a brief synopsis, the function’s arguments and their default
values, and so on. If the documentation seems opaque to you, don’t panic.
You’ll learn more about all these concepts in the next few chapters.
2. Of course, the interactive help mode doesn’t know everything. If you type
something that isn’t a Python command, module, function, or other built-in
keyword, the interactive help mode will just shrug its virtual shoulders.
3. To quit the interactive help mode, type quit and then press Enter.
4. The prompt changes back to >>> to signal that you’ve left the interactive help
mode and returned to the Python shell.
IDLE, the graphical Python shell, also includes a Python—aware text editor. You’ll see how to use it in
the next chapter.

Python Editors and IDEs


IDLE is not the only game in town when it comes to writing programs in Python. While IDLE is useful to
get started with learning the language itself, many developers prefer other text editors or integrated
development environments (IDEs). I won’t cover them here, but the Python community maintains a list
of Python-aware editors at http://wiki.python.org/moin/PythonEditors that covers a wide range of
supported platforms and software licenses.

xlix
Random documents with unrelated
content Scribd suggests to you:
prejudices which even now are so astonishing a feature of German social
life, and which were then even more powerful and far-reaching. That the
Prince and Princess should appear actually to enjoy the society of mere
painters and writers and scientists, whether they occupied any official
positions or not, seemed extraordinary and highly improper to the whole
bureaucratic element of Berlin, and must, we can well imagine, have
seriously offended the Prince’s father.
It is easy to be wise after the event. No one now can help seeing that it
would have been the truest wisdom for the young Princess to have rigidly
suppressed her natural tastes and intellectual interests, and to have led a life
of the narrowly conventional character which Prussian princesses were
expected to lead. But she was incapable of such self-suppression, which
would have seemed to her deceitful, and the mild cautions and hints at
prudence in her father’s letters were pathetically inadequate to the needs of
her critical position. She was herself still quite unaware of how closely she
was being watched and criticised. “I am very happy,” she told a guest at one
of the Court receptions, “and I am intensely proud of belonging to this
country.”
The more the Princess’s social preferences aroused the suspicion and
indignation of the Court world, the more popular she became with the
“intellectuals,” unfortunately not a profitable exchange for her as she was
then situated. We become aware of this by a passage in the Reminiscences of
Professor Schellbach, who had been mathematical tutor to Prince Frederick
William. He writes:
“The first words which the Princess addressed to me with the greatest
kindness were, ‘I love mathematics, physics, and chemistry.’ I was much
pleased, for I saw that the Prince must have given her a pleasant account of
me. Under the direction of her highly cultivated father, who had himself
studied it, Princess Victoria had become acquainted with natural science, and
had even received her first teaching from such famous men as Faraday and
Hoffman. Our beloved Princess soon revealed her love for art and science, as
well as her pleasure in setting problems of her own. Her Royal Highness at
first tried to go on with her studies in physics and mathematics under my
direction, but soon her artistic work took up the remainder of time which the
requirements of Court life left to her.”
Early in June Prince Albert carried out his plan of visiting his daughter
and son-in-law, but it was at Babelsberg, not at Coburg, as he had hoped. He
was able to report to Queen Victoria: “The relation between the young
people is all that can be desired. I have had long talks with them both, singly
and together, which gave me the greatest satisfaction.”
Prince Albert was, however, shocked to find the King of Prussia in a
terrible state:
“The King looks frightfully ill; he was very cordial and friendly, and for
the half hour he stayed with us, did not once get confused, but complained
greatly about his state of health. He is thin and fallen away over his whole
body, with a large stomach, his face grown quite small. He made many
attempts at joking in the old way, but with a voice quite broken, and features
full of pain. ‘Wenn ich einmal fort bin, wieder fort bin,’ he said, grasping his
forehead and striking it, ‘then the Queen must pay us a visit here, it will
make me so happy.’ What he meant was, ‘Wenn ich wieder wohl bin.’ ‘It is
so tedious,’ he murmured; thus it is plainly to be seen that he has not quite
given up all thought of getting better. The Prince’s whole aim is to be
serviceable to his brother. He still walks very lame, but looks well. I kept
quietly in the house all day with Vicky, who is very sensible and good.”
The Princess had special reasons for being “sensible” at this time, for, to
the great joy of the Prussian Royal family, she was enceinte.
In August Queen Victoria and the Prince Consort paid a visit of some
length to their daughter. The Queen herself describes the visit as “quite
private and unofficial,” although she carried in her train not only Lord
Malmesbury, the Foreign Secretary in Lord Derby’s Government (which had
been formed in February), but also Lord Clarendon, his predecessor, and
Lord Granville, who had been Lord President of the Council in Palmerston’s
Government.
Prince Albert, at any rate, did not neglect the opportunity of studying the
political situation. He wrote to Stockmar a letter highly approving the Prince
of Prussia’s political views, while his son-in-law he described as firm in his
constitutional principles and despising the Manteuffel Ministry, the members
of which he met with obvious coolness.
The Berliners gave a hearty reception to Queen Victoria and Prince
Albert, and the Queen declared to the Burgomaster of Berlin that she felt
exceedingly happy there, because she had realised with what love and
devotion everyone was attached to the Royal house and to her daughter.
She was delighted with old Wrangel, whom she calls a great character.
“He was full of Vicky and the marriage, and said she was an angel.” There
was a great deal of sight-seeing, mitigated by charming little gemuthlich
family dinners, and a grand review at Potsdam.
Prince Albert’s birthday occurred during the visit, and one of the Queen’s
presents to him was “a paper-weight of Balmoral granite and deer’s teeth
designed by Vicky.” “Vicky gave her portrait, a small oil one by Hartmann,
very like though not flattered, and a drawing by herself. There were two
birthday cakes. Vicky had ordered one with as many lights as Albert
numbered years, which is the Prussian custom.”
Her Majesty notes with pleasure the arrival of “our dear, excellent old
friend Stockmar,” whose presence, however, by no means gave universal
satisfaction. Indeed, Sir Theodore Martin says frankly that, although his visit
was due solely to his desire to meet the Queen and Prince Consort, it was
viewed with rancorous suspicion by the aristocratic party, who held in
abhorrence the man whom they knew to be the great advocate for the
establishment of constitutional government in Germany. He was even
accused of actively intriguing for the downfall of the Manteuffel
Administration, having, it was said, “brought in his pocket, all cut and dry
from England, the Ministry of the new era.”
Stockmar’s views of what was needful to raise Germany to her proper
place among the nations were unchanged, but age and infirmity had for some
time made him a mere looker-on. Nevertheless, it is probable that neither the
Queen nor Prince Albert in the least realised how inadvisable, in the interests
of the Princess Royal, was the old man’s visit.
It must not, however, be thought that the Prussians were indifferent to the
Princess Royal’s singular personal charm. We have a most interesting
glimpse of this in a long letter written to Queen Victoria by the beautiful and
brilliant Duchess of Manchester, herself a Hanoverian by birth, who
afterwards married the Duke of Devonshire and for many years held a
remarkable position in English society.
The Duchess relates how well the Princess Royal was looking during the
manœuvres on the Rhine, and how much she seemed to be beloved, not only
by all those who knew her, but also by those who had only seen and heard of
her.
“The English could not help feeling proud of the way the Princess Royal
was spoken of, and the high esteem she is held in. For one so young it is a
most flattering position, and certainly, as the Princess’s charm of manner and
her kind unaffected words had in that short time won her the hearts of all the
officers and strangers present, one was not astonished at the praise the
Prussians themselves bestow on her Royal Highness. The Prussian Royal
Family is so large, and their opinions politically and socially sometimes so
different, that it must have been very difficult indeed at first for the Princess
Royal, and people therefore cannot praise enough the high principles, great
discretion, sound judgment, and cleverness her Royal Highness has
invariably displayed.”
And the Duchess adds, on the authority of Field Marshal Wrangel, that
the soldiers were particularly delighted to see the Princess on horseback and
without a veil.
The Royal visit to Babelsberg came to an end all too soon, and the leave-
taking was tearful and emotional in the extreme. Queen Victoria wrote with
natural feeling, “All would be comparatively easy, were it not for the one
thought that I cannot be with her at the very critical moment when every
other mother goes to her child!”
In October of that first year of the Princess Royal’s married life, her
father-in-law became permanent Regent, owing to the continued mental
incapacity of King Frederick William IV. This filled the young Princess with
intense satisfaction, which was increased when the new Prince Regent
declared it to be his intention strictly to adhere to the letter and the spirit of
the Constitution of 1850. The great bulk of the nation rallied instantly round
him, and it seemed as if the gulf between the House of Hohenzollern and the
people of Prussia had been suddenly bridged. The Manteuffel Ministry fell
in the following month, a general election produced an enormous Liberal
majority, and the hopes of the Constitutionalists ran high. The Manteuffel
Ministry was succeeded by one of which Prince Charles Anthony of
Hohenzollern was the President. From this time forward Prince Frederick
William regularly attended the meetings of the Ministry, and Privy
Councillor Brunnemann was assigned to him as a kind of secretary and
channel of communication on State affairs.
The Princess Royal imprudently expressed to a gentleman of the Court
her satisfaction at the change in the political situation, and her words, being
repeated and exaggerated, gave great offence to the Conservative party,
which was also the party of the King. The Princess’s satisfaction was of
course shared by her father, who wrote to the sympathetic Stockmar a letter
showing no prevision of that great rock of Army administration on which
these high hopes were destined to be wrecked:
“The Regency seems now to have been secured for the Prince. We have
only news of this at present by telegrams from our children, but are greatly
delighted at this first step towards the reduction to order of a miserable
chaos. Will the Prince have the courage to surround himself with honourable
and patriotic men? That is the question, and what shape will the new
Chamber take, and what will its influence on him be?”
On November 20, 1858, Prince and Princess Frederick William moved
into the palace in Unter den Linden which was henceforth to be their
residence in Berlin; and on the following day, the Princess’s eighteenth
birthday, there was a kind of dedicatory service in the palace chapel, which
was attended by all the members of the Royal House.
HER ROYAL HIGHNESS
VICTORIA, PRINCESS ROYAL
1856

This palace had been the scene of the happy life of the Prince’s
grandfather, King Frederick William III, and of Queen Louise. The intimate
and beautiful family life that had filled these rooms was the best of omens
for the young pair, and the Princess Royal was delighted with her new home.
But the palace required to be brought up to modern standards of comfort,
and it was very difficult to have the alterations approved by the moody and
violent King. What he allowed on one day he took back with hasty blame on
the morrow. At last Prince Frederick William obtained the Royal assent to
those alterations which were absolutely urgent, together with a grant of
350,000 thalers. Among other improvements was added an eight-cornered
“Gedenkhalle” or “Memory-Hall,” in which were placed the numerous
wedding presents of the young pair, and to these, from time to time, were
added other rare and beautiful objects.
CHAPTER VI

BIRTH OF PRINCE WILLIAM


ON January 27, 1859, Berlin was on the tip-toe of expectation. The custom is
that 101 guns announce the birth of a Prince, and only twenty-one that of a
Princess, and as in Prussia the Salic Law still obtains, it may easily be
imagined with what anxiety the Berliners counted the successive discharges.
There was indeed no need to wait for the whole tale of the 101 guns, for the
firing of the twenty-second was enough to spread the glad news.
The story goes that when old Field-Marshal Wrangel, “Papa Wrangel” as
the Berliners affectionately called him, left the palace, the populace crowded
round him and demanded to know what he could tell them. “Children,” he
answered, “all is well! It is as fine and sturdy a recruit as one could wish!”
It soon became known, however, that all had not gone well with the
young mother and her child. There had been one of those unfortunate
mishaps, the exact truth of which it is always so difficult to disentangle, but
the following account, we believe, represents what actually happened:
It had been Queen Victoria’s wish that the Princess should be attended in
her confinement by Dr. Martin, her English doctor, as well as the German
Court physicians. About eight o’clock in the morning of January 27, one of
the latter wrote to his English colleague, asking him to come at once to the
Palace. But the servant to whom the letter was entrusted, instead of taking it
to Dr. Martin’s house, put it in the post, and it never reached him till the
afternoon. To that fact the Princess Royal’s friends always attributed the
circumstances which resulted in the weakness of the infant’s left arm. Be
that as it may, both mother and baby were for a time in imminent danger. No
anæsthetic was administered, and the Princess with characteristic courage
looked up to her husband, who held her in his arms the whole time, and
asked him to forgive her for being impatient. None of those about her
thought her strength would hold out, and one of the German doctors actually
said in her presence that he thought she would die, and her baby too. But at
last her ordeal came to an end, and to her intense joy she was told that she
had given birth to a fine healthy boy.
The news of the birth of their first grandchild was quickly flashed to the
anxious parents at Windsor. “A boy,” ran the telegram, and Queen Victoria
characteristically replied, “Is it a fine boy?” But it was not till the following
day, so Prince Albert told Stockmar, that the courier brought “our first
information of the severe suffering which poor Vicky had undergone, and of
the great danger in which the child’s life had hovered for a time.” To King
Leopold the Prince wrote, “The danger for the child and the sufferings for
the mother were serious. Poor Fritz and the Prince and Princess must have
undergone terrible anxiety, as they had no hope of the birth of a living child,
and their joy over a strong, healthy boy is therefore all the greater.”
On the evening of the baby’s birth, the Prince Regent, also a grandfather
for the first time, held a reception of which we have a vivid description from
the pen of the dramatist, Gustav zu Putlitz, then a member of the Prussian
Landtag, and afterwards chamberlain to Princess Frederick William. He
says:
“It was like a great family festival. Everyone hurried there with
congratulations, and when the young father, beaming with happiness,
appeared, the rejoicings increased. This delight is shared by all classes of
society, and is a testimony to the extent of the popularity of the Prince and
Princess.”
Prince Frederick William received on January 29 the congratulations of
the Prussian Chambers, to which he made the following reply:
“I thank you very heartily for the interest you have shown in the joyful
event, which is of such consequence to my family and to the country. If God
should preserve my son’s life, it shall be my chief endeavour to bring him up
in the opinions and sentiments which bind me to the Fatherland. It is nearly a
year to-day since I told you how deeply moved I was by the universal
sympathy which was exhibited towards me, as a young married man, by the
country as a whole. This sympathy it was which made the Princess, my wife,
who had left her home to come to a new Fatherland, realise those ties of
affection which have now, owing to the birth of this son, become
unbreakable. May God therefore bless our efforts to bring up our son to be
worthy of the love which has been thus early manifested towards him. The
Princess, to whom I was able to communicate your intention, desires me to
express her most sincere thanks.”
The christening was fixed for March 5, but neither of the parents of the
Princess could be present. “I don’t think I ever felt so bitterly disappointed,”
wrote the Queen to Uncle Leopold. “It almost breaks my heart. And then it is
an occasion so gratifying to both nations and brings them so much together
that it is peculiarly mortifying.” However, the Queen consoled herself by
doing all she could to mark the importance of the occasion. She sent a
formal mission to represent her and the Prince Consort at the christening,
consisting of Lord Raglan, the son of the victor of the Alma, Inkerman, and
Balaclava, and Captain (afterwards Lord) de Ros, equerry to Prince Albert.
They were both old friends of the Princess, to whom her father wrote:
“I was certain that the presence of Lord Raglan and Captain de Ros
would give you pleasure. Ours will come when they return, and we can put
questions to them. My first will be: Has the Princess gone out and does she
begin to enjoy the air, to which alone she can look for regaining strength and
health? Or is she in the way to grow weak and watery by being baked like a
bit of pastry in hot rooms? My second: Is she grown? I will spare you my
others.
“Your description of the Prince’s kindness and loving sympathy for you
makes me very happy. I love him dearly, and respect and value him, and I
am glad too, for his sake, that in you and my little grandchild he has found
ties of family happiness which cannot fail to give him those domestic tastes,
in which alone in the long run life’s true contentment is to be found.”
The baby Prince was duly christened on March 5, when he received the
names of Frederick William Victor Albert, and on the following day his
parents issued a touching expression of their gratitude for the sympathy and
congratulations they had received from the public. In it they pledged
themselves afresh to bring up their son, with the help of God, to the honour
and service of the Fatherland.
After the special envoys had returned from Berlin, the Prince writes to his
daughter a letter on the duties of motherhood, which was decidedly candid
for those rather prudish days:
“Lord Raglan’s and Captain de Ros’s news of you have given me great
pleasure. But I gather from them that you look rather languid and exhausted.
Some sea air would be the right thing for you; it is what does all newly-made
mothers the most good when their ‘campaign is over.’ I am, however,
delighted to hear you have begun to get into the air. Now pass on as soon as
possible to cold washing, shower baths, &c., so as to brace the system again,
and to restore elasticity to the nerves and muscles.
“You are now eighteen years old, and you will hold your own against
many a buffet in life; still, you will encounter many for which you were not
prepared and which you would fain have been spared. You must arm
yourself against these, like Austria against the chance of war, otherwise you
will break down and drop into a sickly state, which would be disastrous to
yourself, and inflict a frightful burden upon poor Fritz for life; besides
which, it would unfit you for fulfilling all the duties of your station.
“In reference to having children, the French proverb says: Le premier
pour la santé, le second pour la beauté, le troisième gâte tout. But England
proves that the last part of the saying is not true, and health and beauty, those
two great blessings, are only injured where the wife does not make zealous
use of the intervals to repair the exhaustion, undoubtedly great, of the body,
and to strengthen it both for what it has gone and what it has to go through,
and where also the intervals are not sufficiently long to leave the body the
necessary time to recruit.”
The Princess had a favourable convalescence, during which her active
mind was troubled by an article on Freemasonry. Her father, to whom of
course she turned for counsel, had never consented to be initiated as a
Mason, though his sons, King Edward and the Duke of Connaught, both
became enthusiastic members of the craft. The Princess seems to have been
troubled by the idea that her husband’s connection with the order—he had
been appointed patron of the Masonic Lodges of Prussia and head of the
Grand Lodge in Berlin—would in some way lessen the confidence between
them. Prince Albert endeavours to reassure her with a paradox which she
probably found quite unconvincing:
“I will get Alice to read to me the article about Freemasons. It is not
likely to contain the whole secret. The circumstance which provokes you
only into finding fault with the Order, namely that husbands dare not
communicate the secret of it to their wives, is just one of its best features. If
to be able to be silent is one of the chief virtues of the husband, then the test
which puts him in opposition to that being towards whom he constantly
shows the greatest weakness, is the hardest of all, and therefore the most
compendious of virtues, and the wife should not only rejoice to see him
capable of withstanding such a test, but should take occasion out of it to vie
with him in virtue by taming the inborn curiosity which she inherits from her
mother Eve. If the subject of the secret, moreover, be nothing more
important than an apron, then every chance is given to virtue on both sides,
without disturbing the confidence of marriage, which ought to be complete.”
The baby Prince William thrived, in spite of the defect in his left arm,
which was shorter than the other. We have some entertaining glimpses of
him, and of his parents’ pride in him, in the correspondence of Priscilla Lady
Westmorland. A German friend of hers, a lady of high rank, wrote to Lady
Westmorland when the Prince was only about a week old:
“I must tell you of my wonderful good fortune—I have actually seen this
precious child in his father’s arms! You will ask me what this child of so
many prayers and wishes is like. They say all babies are alike: I do not think
so: this one has a beautiful complexion, pink and white, and the most lovely
little hand ever seen! The nose rather large; the eyes were shut, which was as
well, as the light was so strong. His happy father was holding him in his
arms, and himself showed traces of all he has gone through at the time. The
child was believed to be dead, so you may conceive the ecstasy of everyone
at his first cry.”
Prince Frederick William was indeed, as this lady put it, beside himself
with joy. He delighted in showing his baby to his friends and loyal servants,
calling him “mein Junge.”
In the early summer of 1859 the Princess Royal spent a happy holiday at
Osborne, and her English relatives and friends thought her extraordinarily
well and happy; it was also considered that she had become much better
looking. The Queen describes her as “flourishing, and so well and gay,” and
as “a most charming companion,” while Prince Albert tells Stockmar that
“We found Vicky very well, and looking blooming, somewhat grown, and in
excellent spirits. The short stay here will certainly be beneficial both to her
health and spirits.”
While the Princess was in England, she was asked by her parents if she
would make private inquiries as to any German princesses who might be
suited to become Princess of Wales, but the search does not seem to have
been successful. It was then that Sir Augustus Paget, who had been for two
years British Minister in Copenhagen, spoke to his fiancée, the Princess
Royal’s lady-in-waiting, of Princess Alexandra. It was from this lady, now
Walpurga Lady Paget, that Queen Victoria and the Prince Consort first heard
of the beauty and many endearing graces of the Danish princess. So
impressed were they by her account that it was arranged that the Princess
Royal should meet Princess Alexandra informally at Strelitz, in the palace of
the Grand Duchess of Mecklenburg.
This meeting duly took place, and the Princess Royal wrote most
enthusiastically of the result of their informal interview. It was directly
owing to this fact that it was settled that the Prince of Wales and Princess
Alexandra should meet, as if by chance, in the cathedral of Spiers with a
view to making close acquaintance.
The birth of Prince William brought a considerable change in the lives of
his parents. Babelsberg had become too small to make a convenient summer
home, and so the King granted them the use of the New Palace at Potsdam,
which is only about half an hour’s journey from Berlin.
This enormous rococo building with its two hundred rooms was erected
by Frederick the Great at the end of the Seven Years’ War, in order to show
his enemies that he had plenty of money still left with which to go to war
again if necessary. Prince Frederick William was very fond of the New
Palace, where he had himself been born, and which was full of reminders of
his great namesake. Apparently the only thing he did not like about it was its
name, for it will be remembered that during his brief reign he altered it to
Friedrichskron.
Queen Victoria, on her visit to Babelsberg in August, 1858, had gone to
see the Palace, and she describes it in her diary as “a splendid building that
reminded me much of Hampton Court—the same colour, same style, same
kind of garden, with splendid orange trees which in the cool calm evening
sent out a delicious smell. The Garten-Saal, one enormous hall, all in marble
with incrustations of stones, opening into a splendid room or gallery,
reminded me of the Salle des Glaces at Versailles. There is a theatre in the
Palace, and many splendid fêtes have been given there. There are some
rooms done in silver, like those at Sans Souci and Potsdam, and all in very
rich Renaissance style. The millions it must have cost! But none of these
palaces is wohnlich (liveable in). None like dear Babelsberg!”
The Princess Royal was determined to make at any rate her own rooms in
the Palace wohnlich. After the fashion of the period, she surrounded herself
with portraits of her relations, and with paintings of her various beloved
English homes. There were endless souvenirs of her childhood scattered
about in her rooms—souvenirs of her Christmases and of birthdays, little
gifts presented to her as a child and young girl by her grandmother, by her
“Aunt Gloucester,” and by all those who had surrounded her during the days
of her happy youth.
It is curious to reflect that, twenty years after the Princess Royal first took
up her residence there, an English visitor was to write: “Without Carlyle’s
Frederick the Great, Potsdam would be a collection of mere dead walls
enclosing a number of costly objects. Illuminated by the book, each room,
each garden wall thrills with human interest.” But when the Princess Royal
first went there to make the New Palace her home for a part of each year, it
might much more truly have been described as an arid and dusty waste, and
that though it was surrounded by many waters. The gardens were very stiff,
indeed ugly, but the Princess’s active, creative mind saw their possibilities,
and under her fostering hand and taste they were transformed and made to
yield the utmost of beauty and delight.
The New Palace henceforth became associated, in the minds of all those
who were truly attached to the Princess, with all that was best and most
peaceful in her life. It was there that she was able to set the example of that
helpful and happy country life which she had learned to value in England,
and it was not long before its simple domestic character became known far
and wide, and exercised an influence the extent of which it is impossible to
estimate.
The Prince and Princess had a farm at Bornstedt, not far off, and there the
Prince delighted to become for the time a simple farmer, managing himself
all the details of the crops and the labourers, while the Princess occupied
herself with the poultry and her model dairy. It may, indeed, be doubted
whether the Prince and Princess found the farm a very good investment
financially, but that was of small importance compared with the spiritual
refreshment which they derived from this close periodical contact with the
simple, natural gifts of mother earth.
Among the neighbouring villagers, too, they found plenty of scope for the
exercise of an intelligent philanthropy, in gradually modifying the primitive
ideas then prevalent on sanitation, and in caring for the children and the old
people. The Prince would himself sometimes teach in the village schools. A
pretty story is told that one day, when he was questioning a class, he asked a
little girl to what kingdom his watch-chain and a flower in his button-hole
respectively belonged, and when she had answered correctly, he went on to
ask, “To what kingdom do I belong?” and the child replied, “To the kingdom
of Heaven.”
In June, 1859, the war between Austria and the allied French and
Sardinian armies, culminating in the defeat of the Austrians at Solferino,
brought natural anxieties to the Princess. The Prince Regent, while declaring
the neutrality of Prussia, nevertheless ordered a mobilisation of the Army for
the protection of Germany, and Major-General Prince Frederick William,
commanding the First Infantry Brigade of Guards, was appointed to the
command of the First Infantry Division of Guards. Though the Princess, thus
early in her married life, showed by her quietude that she was a true soldier’s
wife, it was a great relief to her when the threatened danger was over and the
mobilisation rescinded on the conclusion of the Peace of Villafranca in July.
Prince Frederick William’s promotion to command a division was then
confirmed by his father.
The political situation, however, remained difficult, and Prince Albert and
his daughter watched it with anxious concern. The following passage in a
letter of his dated September is no doubt in reply to some comments of hers
on the position of Prussia and Germany in view of the rising agitation for
unity in Italy:
“I am for Prussia’s hegemony; still Germany is for me first in importance,
Prussia as Prussia second. Prussia will become the chief if she stand at the
head of Germany: if she merely seek to drag Germany down to herself, she
will not herself ascend. She must, therefore, be magnanimous, act as one
with the German nation in a self-sacrificing spirit, prove that she is not bent
on aggrandisement, and then she will gain pre-eminence, and keep it,” and
he goes on to point the moral in the sacrifices which Sardinia had already
made for the Italian idea.
In November the Princess Royal paid a visit to England with her husband
in time to celebrate the Prince of Wales’s birthday on the 9th, and Prince
Albert tells Stockmar:
“We find the Princess Royal looking extremely well, and in the highest
spirits, infinitely lively, loving, and mentally active. In knowledge of the
world, she has made great progress.” The visit lasted till December 3, and
Prince Albert wrote to the Dowager Duchess of Coburg that Prince Frederick
William “has delighted us much. Vicky has developed greatly of late, and yet
remains quite a child; of such indeed is the kingdom of Heaven.”
And after his daughter had gone back to Berlin, the loving father wrote to
her:
“Your dear visit has left upon us the most delightful impression; you were
well, full of life and freshness, and withal matured. I may therefore yield to
the feeling, sweetest of all to my heart as your father, that you will be
lastingly happy. In this feeling I wait without apprehension for what fate
may bring.”
On this visit to England the Princess did not fail to see her old friend and
ruler, Sarah Lady Lyttelton, who records:
“The dear Princess came in, habited and hatted and cockfeathered from
her ride, looking very well though in a very bad cold. She embraced me and
received me most kindly, and took me into her magnificent sitting-room,
where I spent almost an hour with her, till she had to go and change her dress
for luncheon. She talked much of her baby and inquired after everybody
belonging to me and seemed as happy as ever.”
CHAPTER VII

ADVICE FROM ENGLAND


THE year 1860 was on the whole a happy one for the Princess Royal. It
brought her a long visit from her parents and the birth of her eldest daughter,
but on the other side of the account the relations between her two countries,
England and Prussia, became perceptibly worse.
For the New Year her father sent her one of his customary letters of
sagacious counsel, in which may be detected a certain note of uneasiness as
to the development of his daughter’s powers of self-control:
“You enter upon the New Year with hopes, which God will surely
graciously suffer to be fulfilled, but you do also with good resolutions,
whose fulfilment lies within your own hand and must necessarily contribute
to your success, also happiness, in this suffering and difficult world. Hold
firmly by these resolutions, and evermore cherish the determination, with
which comes also strength, to exercise unlimited control over yourself, that
the moral law may govern and the propensity obey,—the end and aim of all
education and culture, as we long ago discovered and reasoned out together.”
It is remarkable that early in this year Prince Frederick William appears
to have been for a time the centre of the hopes of the reactionary party. The
Junkers actually planned to bring about the resignation of the Prince Regent,
and to induce Prince Frederick William to assume the supreme power and
govern without a constitution, which formed the great obstacle to their
military ambitions. This scheme argued an extraordinary misapprehension,
not only of Prince Frederick William’s honest, straightforward character, but
also of all his political ideals. He was, especially at this period of his life, a
pure Constitutionalist, with a profound admiration for the free polity of
England, and it would be difficult to imagine any form of government which
would have seemed both to him and to his wife more immoral, as well as
more certain to entail a counter-revolution, than a military dictatorship. It is
perhaps not without significance that in March a British warship was
launched at Portsmouth and was named Frederick William by way of
compliment to the husband of the Princess Royal.
In June there was a parade at the Königsberg garrison, at which the Prince
Regent said to his son, “Fritz, I appoint you to the First Infantry Regiment,
the oldest Corps in the service,” and about a month afterwards the young
commander was promoted to the rank of Lieutenant-General.
The Princess Royal’s eldest daughter was born on July 24, and was
christened Victoria Augusta Charlotte, being known as Princess Charlotte till
her marriage in 1878 to the Hereditary Prince of Saxe-Meiningen. Queen
Victoria records the news of the baby’s birth in her usual vivid style:
“Soon after we sat down to breakfast came a telegram from Fritz—Vicky
had got a daughter at 8.10, and both were well! What joy! Children jumping
about—everyone delighted—so thankful and relieved.”
Only the day before there had come a letter from the Princess Royal
containing the intelligence that Prince Louis of Hesse was ardently desirous
of paying his addresses to Princess Alice, the Princess Royal’s much-loved
sister and companion of her childhood. To this Prince Albert refers in writing
to his daughter:
“Only two words of hearty joy can I offer to the dear newly-made mother,
and these come from an overflowing heart. The little daughter is a kindly gift
from heaven, that will (as I trust) procure for you many a happy hour in the
days to come. The telegraph speaks only of your doing well; may this be so
in the fullest sense!
“Upon the subject of your last interesting and most important letter, I
have replied to Fritz, who will communicate to you as much of my answer as
is good for you under present circumstances. Alice is very grateful for your
love and kindness to her, and the young man behaves in a manner truly
admirable.”
A few days later the anxious father writes to the young mother one of his
curious medical homilies:
“I hope you are very quiet, and keep this well in mind, that although you
are well, and feel yourself well, the body has to take on a new conformation,
and the nervous system a new life. Only rest of brain, heart, and body, along
with good nourishment, and its assimilation by regular undisturbed
digestion, can restore the animal forces. My physiological treatise should not
bore you, for it is always good to keep the GREAT PRINCIPLES in view, in
accordance with which we have to regulate our actions.”
But it was not all physiological treatise that was despatched from
Osborne to Berlin. The Prince has an amusing reference to the busy
importance with which the little Princess Beatrice, who was then three and a
quarter years old, regarded the arrival of her first niece:
“The little girl must be a darling. Little maidens are much prettier than
boys. I advise her to model herself after her Aunt Beatrice. That excellent
lady has now not a moment to spare. ‘I have no time,’ she says, when she is
asked for anything, ‘I must write letters to my niece.’
“It will make you laugh, if I tell you that I have christened a black mare
Ayah (as black nurse). I lately asked the groom what was the horse’s name,
which I had forgotten. ‘Haya,’ was the answer. ‘What?’ I asked. ‘We spell it
Hay, Why, Hay.’ You should call your Westphalian nurse, ‘Hay, Why, Hay!’”
It had been arranged that the Queen and Prince Albert should pay their
visit to their daughter and son-in-law at Coburg at the end of September. By
a most unfortunate chance there had occurred about the middle of the month
one of those “incidents” which are sometimes, when mishandled by
officialdom and magnified by offended national pride, allowed to exercise an
influence ludicrously disproportionate to their real triviality. The Macdonald
affair, as it was called, at one moment threatened to bring about a serious
breach between England and Prussia, and as it was unquestionably one of
the causes of the dislike and suspicion with which the Princess Royal was to
be regarded by a section of the Prussians, it is worth while to record it in
some detail.
A Scottish gentleman, a certain Captain Macdonald, had a dispute about a
seat in a railway carriage at Bonn. He knew no German, was ignorant of
Prussian law, and very likely behaved, or was considered by the authorities
to have behaved, in an autocratic manner. However that may be, he was not
only ejected from the carriage but was committed to prison, where he
remained from September 12 to 18. On the 18th he was tried and fined
twenty thalers and costs. The English residents at Bonn warmly espoused his
cause, and Captain Macdonald seems, apart from the original dispute, to
have had reason to complain of violence used to him and also of his
treatment while in prison. It was also particularly unfortunate that at the trial
the Staatsprocurator, or public prosecutor, should have denounced the
behaviour when abroad of English people generally. “The English residing
and travelling,” he said, “are notorious for the rudeness, impudence, and
boorish arrogance of their conduct.”
This accusation, whether well founded or not, naturally seemed to
English lawyers and the English public a piece of gratuitous irrelevance,
intended merely to excite prejudice against Captain Macdonald. It is
impossible now to apportion the blame for the way in which the incident was
allowed to embitter public opinion in both countries. The affair dragged on
for months—indeed, it was not finally disposed of till the following May.
There were questions in Parliament, Lord Palmerston was extremely angry,
and an article in the Times served to pour oil on the flame.
In the circumstances the incident inevitably rather dashed the joy of the
happy family party at Coburg. The Queen conferred with Lord John Russell,
then Foreign Secretary, whom she had brought with her, and she alludes in
her journal to “the ejection and imprisonment (unfairly, it seems) of a
Captain Macdonald, and the subsequent offensive behaviour of the
authorities. It has led to ill blood, and much correspondence, but Lord John
is very reasonable about it, and not inclined to do anything rash. These
foreign governments are very arbitrary and violent, and our people apt to
give offence, and to pay no regard to the laws of the country.”
The Queen and Prince Albert arrived at Coburg on September 25, and the
Princess Royal delighted in visiting with her father the scenes of his
boyhood. She went with the guns to a drive of wild boars, and almost every
day there was an expedition to some interesting place in all the relief of
incognito. One day Prince Albert had a narrow escape. He was alone in an
open carriage when the horses ran away. With great presence of mind, he
jumped out, and happily got off with nothing worse than a few cuts and
bruises. Gustav Freytag, the distinguished German novelist and dramatist,
was received, and the Queen records that there was much conversation with
him after dinner. As we shall see later, Freytag was admitted to the
confidence of the Princess Royal and her husband, and he repaid their
kindness in strange fashion.
It was on this visit that the Queen saw her eldest grandchild for the first
time. Writing on September 25, she says:
“Our darling grandchild was brought. Such a little love! He came walking
in at Mrs. Hobbs’s [his nurse’s] hand, in a little white dress with black bows,
and was so good. He is a fine, fat child, with a beautiful white soft skin, very
fine shoulders and limbs, and a very dear face, like Vicky and Fritz, and also
Louise of Baden. He has Fritz’s eyes and Vicky’s mouth, and very fair curly
hair. We felt so happy to see him at last!”
This was the beginning of an enduring friendship between grandmother
and grandson, and no one with any historical imagination can help recalling
the last scene of that friendship, when this fine little boy, grown to be a
mighty Emperor, hastened to share the grief of the English people at the
death-bed of their great Queen.
The Queen was evidently much attracted by the already characteristic
energy of the little Prince, for there are references to him all through her
records of this visit:
“Dear little William came to me as he does every morning. He is such a
darling, so intelligent.” “Dear little Wilhelm as usual with me before dinner
—a darling child.” “The dear little boy is so intelligent and pretty, so good
and affectionate.” “Had a last visit from dear Stockmar. Towards the end of
his stay, dear little William came in and played about the room.” “The
darling little boy with us for nearly an hour, running about so dearly and
merrily.” “At Cologne our darling little William was brought into our
carriage to bid good-bye. I felt the parting deeply.”
Prince Albert wrote to the Duchess of Kent: “Your great-grandson is a
very pretty, clever child—a compound of both parents, just as it should be.”
Mrs. Georgina Hobbs, the nurse mentioned above, first went to Germany
as a maid in the service of the Princess Royal on her marriage, and was
afterwards promoted to be chief nurse to the Royal children. Prince William
and his brother and sisters were devotedly attached to “Hobbsy,” as they
called her, and it was from “Hobbsy” that they learnt English, for their
parents always talked German to one another.
The Princess Royal, perhaps naturally, preferred to have her children’s
nursery arranged and conducted on the English rather than on the German
model, but who can doubt that in this, as in other matters of even less
importance, she would have done better to have studied the susceptibilities
of her adopted country? Indeed, Dr. Hinzpeter, who was afterwards
appointed the tutor of her sons, bears witness that her nursery management
became a great subject of gossip among the Berliners, and stories were even
current of corporal punishment administered before the Court to princes with
dirty faces. It is true that Dr. Hinzpeter describes these stories as mythical,
but the fact that they were circulated and believed helps to account for the
Princess’s growing unpopularity.
At this period Prince Albert was seriously disturbed by the attacks which
the Times was constantly making on Prussia and everything Prussian. In an
article in the Saturday Review, recommended by him to his daughter, it was
said: “The only reason the Times ever gives for its dislike of Prussia, is that
the Prussian and English Courts are connected by personal ties, and that
British independence demands that everything proceeding from the Court
should be watched with the most jealous suspicion.”
The Prince was honestly indifferent to the insinuations against himself by
which these attacks were frequently pointed, but he was reasonably anxious
about the bad effect they would have in Germany. Writing to his daughter on
October 24, after his return to England, he refers to the Macdonald affair,
which had already become acute:
“What abominable articles the Times has against Prussia! That of
yesterday upon Warsaw and Schleinitz is positively too wicked. It is the
Bonn story which continues to operate, and a total estrangement between the
two countries may ensue, if a newspaper war be kept up for some time
between the two nations. Feelings, and not arguments, constitute the basis
for actions. An embitterment of feeling between England and Prussia would
be a great misfortune, and yet they are content in Berlin to make no move in
the Bonn affair.”
It was only too true that the Prussian Government was in no hurry to
settle the Macdonald affair. The bitterness which it engendered did not die
out till long after its formal termination in May of the following year, and
undoubtedly it contributed far more than was suspected at the time to
increase the delicacy and difficulty of the Princess Royal’s position. It was
actually thought in Germany that she inspired the attacks in the British Press.
“This attitude of the English newspapers preys upon the Princess Royal’s
spirits and materially affects her position in Prussia,” so wrote Lord
Clarendon.
This autumn and winter Prince Albert, in spite of many political and other
anxieties and a sharp attack of illness, faithfully continued to instruct his
daughter in the art of government.
It does not seem ever to have crossed his mind that such instruction,
though admirable in itself, was ill-advised in view of his pupil’s position.
The ideal woman in Prussia was then, and still is to a large extent, one who,
conscious of her intellectual inferiority, contents herself with managing her
household and children. If this view obtained with regard to women in
private stations, much more was it considered to be the duty of princesses of
the Royal House to abstain from any active interest in public affairs. But
either Prince Albert did not appreciate this, or it is possible that he thought
his daughter to be freed by her exceptional ability from the ordinary
restrictions and limitations of her rank. There is yet a third possibility—that
he did not altogether trust his son-in-law’s political judgment, and was
anxious to give him, in the troublous times that seemed impending, an help-
meet who could influence him in the right, that is in the Coburg, direction.
Whatever may have been the reason, the Prince certainly continued to the
end of his life to cultivate his daughter’s knowledge and grasp of public
affairs.
In December, 1860, the Prince Consort received from Berlin a
memorandum upon the advantages of a law of Ministerial responsibility. Its
object was to remove the apprehensions entertained in high quarters at the
Prussian Court as to the expediency of a measure of this kind. This
memorandum was the work of the Princess Royal, and it is easy to imagine
what a storm of indignation would have arisen in Prussia if by any accident
or indiscretion the knowledge that the Princess had written such a paper had
leaked out.
Still, it was undoubtedly an able piece of work. Sir Theodore Martin says
that it would have been remarkable as the work of an experienced statesman;
and, as the fruit of the liberal political views in which the Prince had been at
pains to train its author, it must have filled his mind with the happiest
auguries for her fulfilment of the great career which lay before her. “It would
have delighted your heart to read it,” were his words in writing to Baron
Stockmar.
To his daughter he sent a long and flattering reply beginning: “It is
remarkably clear and complete, and does you the greatest credit. I agree with
every word of it, and feel sure it must convince everyone who is open to
conviction from sound logic, and prepared to follow what sound logic
dictates.”
This pathetic faith in the potency of logic in political affairs is hard to
reconcile with the Prince Consort’s earlier and sounder dictum that feelings,
not arguments, constitute the basis for actions. It is evident from the rest of
the letter that the Princess had laid it down that the responsibility of his
advisers does not in fact impair the monarch’s dignity and importance, but is
really for him the best of safeguards. She had gone on to discuss the
proposition that the patriarchal relation in which the monarchs of old were
supposed to stand towards their people was preferable to the constitutional
system which interposes the Minister between the sovereign and his
subjects. Her father’s comments on this would have seemed to many
Prussians most heretical doctrine to be imparted to their future Queen.
The patriarchal relation, he says, is pretty much like the idyllic life of the
Arcadian shepherds—a figure of speech, and not much more. It was the
fashionable phrase of an historical transition-period. Monarchy in the days
of Attila, of Charlemagne, of the Hohenstaufen, of the Austrian Emperors, of
Louis XI, XII, XIII, XIV, XV, &c., was as little like a patriarchal relation as
anything could be. On the contrary it was sovereignty based upon spoliation,
war, murder, oppression, and massacre. That relation was sedulously
developed in the small German States, whose rulers were little more than
great landed proprietors, during a short period in the eighteenth century, and
was cherished out of a sentimental feeling. It then gave way before the
Voltairean philosophy during the reigns of Frederick II, Joseph II, Louis
XVI, &c., was turned topsy-turvy by the French Revolution, and finally
extinguished in the military despotism of Napoleon.
The Prince went on to say that in the great war of liberation the people
and their princes stood by one another in struggling for the establishment of
civic freedom, first against the foreign oppressor, and then as citizens in their
own country; and the treaties of 1815, as well as the appeal to the people in
1813, decreed constitutional government in every country. The charter was
granted in France, and special constitutions were promised in all the States;
even to Poland the promise of one was made, although there, as well as in
Prussia and Austria, that promise was not kept. Then came the Holy Alliance
and introduced reaction into Germany, France, Spain, and Italy, by dint of
sword and Congress (in 1817-1823). Once more the patriarchal relation was
fostered with the sentimentalism of the Kotzebue school, and the betrayed
peoples were required to become good children, because the Princes styled
themselves good fathers! The July Revolution, and all that has taken place
since then, sufficiently demonstrate that the peoples neither will nor can play
the part of children.
As for the personal government of absolute Sovereigns, Prince Albert
declared that to be a pure illusion. Nowhere does history present us with
such cases of government by Ministers and favourites as in the most absolute
monarchies, because nowhere can the Minister play so safe a game. A Court
cabal is the only thing he has to fear, and he is well skilled in the ways by
which this is to be strangled. History is full of examples. Recent instances
have occurred where the personal discredit into which the Sovereign has
fallen makes the maintenance of the monarchy, not as a form of government,
but as an effective State machine, all but impossible. When, as in the case of
the King of Naples, this result has arisen, all that people are able to say in
defence is, “He was surrounded by a bad set, he was badly advised, he did
not know the state the country was in.” To what purpose, then, is personal
government, if a man in his own person knows nothing and learns nothing?
The Sovereign should give himself no trouble, said the Prince in
conclusion, about details, but exercise a broad and general supervision, and
see to the settlement of the principles on which action is to be based. This he
can, nay, must do, where he has responsible Ministers, who are under the
necessity of obtaining his sanction to the system which they pursue and
intend to uphold in Parliament. This the personally ruling Sovereign cannot
do, because he is smothered in details, does not see the wood for the trees,
and has no occasion to come to an agreement with his Ministers about
principles and systems, which to both him and them can only appear to be a
great burden and superfluous nuisance.
How these doctrines would have been regarded by probably the majority
of Prussians appears from another letter which the Prince wrote a fortnight
later. His daughter had sent him an article from the Conservative Kreuz-
Zeitung, and on it he comments:
“The article expresses in plain terms the view that Monarchy as an
institution has for that party a value only so long as it is based upon arbitrary
will; and so these people arrive at precisely the same confession of faith as
the Red democrats, by reason of which a Republic is certain to prove neither
more nor less than an arbitrary despotism. Freedom and order, which are set
up as political antitheses, are, on the contrary, in fact, synonymous, and the
necessary consequences of legality. ‘The majesty of the law’ is an idea
which upon the Continent is not yet comprehended, probably because people
cannot realise to themselves a dead thing as the supreme power, and seek for
personal power in government or people. And yet virtue and morality are
also dead things, which nevertheless have a prerogative and a vocation to
govern living men—divine laws, upon which our human laws ought to be
moulded.”
Christmas brought the customary exchange of loving gifts. Prince Louis
of Hesse, now the betrothed of Princess Alice, joined the family circle in
England, and Prince Albert writes to his daughter in Berlin:
“Oh! if you, with Fritz and the children, were only with us! Louis was an
accession. He is a very dear good fellow, who pleases us better and better
daily. In my abstraction I call him ‘Fritz.’ Your Fritz must not take it amiss,
for it is only the personification of a beloved, newly-bestowed, full-grown
son.
“But to return to the dear Christmas festival! Your gifts which were there
have caused the highest delight, and those we have yet to expect will be
looked for with impatience. To the latter belong Wilhelm’s bust, Fritz’s
boar’s head—for which in the meantime I beg you will give the lucky
huntsman my hearty thanks. Wilhelm shall be placed in the light you wish
when he issues (I hope unbroken) from his dusty box. The album, which
arrived yesterday morning, is very precious to us, as it enables us to live
altogether beside you—in imagination.
“Prejudice walking to and fro in flesh and blood is my horror, and, alas, a
phenomenon so common; and people plume themselves so much upon their
prejudices, as signs of decision of character and greatness of mind, nay of
true patriotism; and all the while they are simply the product of narrowness
of intellect and narrowness of heart.”
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like