Programming Python 3rded Edition Mark Lutz pdf
download
https://ebookgate.com/product/programming-python-3rd-ed-edition-
mark-lutz/
Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.com
2.
Instant digital products(PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Learning Python 2nd ed Edition Mark Lutz
https://ebookgate.com/product/learning-python-2nd-ed-edition-mark-
lutz/
ebookgate.com
Python pocket reference 5ed. Edition Mark Lutz
https://ebookgate.com/product/python-pocket-reference-5ed-edition-
mark-lutz/
ebookgate.com
Foundations of Python Network Programming 3rd Edition
Brandon Rhodes
https://ebookgate.com/product/foundations-of-python-network-
programming-3rd-edition-brandon-rhodes/
ebookgate.com
Expert Python Programming 2nd Edition Jaworski
https://ebookgate.com/product/expert-python-programming-2nd-edition-
jaworski/
ebookgate.com
3.
Python Programming 4thEdition Singh A.
https://ebookgate.com/product/python-programming-4th-edition-singh-a/
ebookgate.com
Core Python Programming 2nd Edition Wesley Chun
https://ebookgate.com/product/core-python-programming-2nd-edition-
wesley-chun/
ebookgate.com
Ultimate Python Programming 1st Edition Deepali Srivastava
https://ebookgate.com/product/ultimate-python-programming-1st-edition-
deepali-srivastava/
ebookgate.com
Black hat Python Python programming for hackers and
pentesters 1st Edition Seitz
https://ebookgate.com/product/black-hat-python-python-programming-for-
hackers-and-pentesters-1st-edition-seitz/
ebookgate.com
Effective awk Programming 3rd ed Edition Arnold Robbins
https://ebookgate.com/product/effective-awk-programming-3rd-ed-
edition-arnold-robbins/
ebookgate.com
5.
Programming Python, 3rdEdition
By Mark Lutz
...............................................
Publisher: O'Reilly
Pub Date: August 2006
Print ISBN-10: 0-596-00925-9
Print ISBN-13: 978-0-59-600925-0
Pages: 1596
Table of Contents | Index
Already the industry standard for Python users, Programming
Python from
O'Reilly just got even better. This third edition has been updated to
reflect current best practices and
the abundance of changes introduced by the latest version of the
language, Python 2.5.
Whether you're a novice or an advanced
practitioner, you'll find this
refreshed book more than lives up to its reputation. Programming
Python, Third Edition teaches you the right
way to code. It explains Python language syntax and programming
techniques in a clear and concise
manner, with numerous examples that illustrate both correct usage and
common idioms. By reading this
comprehensive guide, you'll learn how to apply Python in real-world
problem domains such as:
GUI programming
Internet scripting
Parallel processing
Database management
Networked applications
Programming Python, Third Edition covers
each of these
target domains
gradually, beginning with in-depth discussions of core concepts and
then progressing toward complete
programs. Large examples do appear, but only after you've learned
6.
enough to understandtheir techniques and
code.
Along the way, you'll also learn how to use the Python language in
realistically scaled programs--concepts such as Object Oriented Programming (OOP) and code
reuse
are recurring side themes throughout this
text. If you're interested in Python programming, then this O'Reilly
classic needs to be within arm's reach. The
wealth of practical advice, snippets of code and patterns of program
design can all be put into use on a
daily basis--making your life easier and more productive.
Reviews of the second edition:
"...about as comprehensive as any book can be."
--Dr. Dobb's Journal
"If the language had manuals, they would undoubtedly
be the texts from O'Reilly...'Learning Python' and 'Programming Python'
are definitive treatments."
--SD Times
7.
Programming Python, 3rdEdition
By Mark Lutz
...............................................
Publisher: O'Reilly
Pub Date: August 2006
Print ISBN-10: 0-596-00925-9
Print ISBN-13: 978-0-59-600925-0
Pages: 1596
Table of Contents | Index
Copyright
Foreword
Preface
Part I: The Beginning
Chapter 1. Introducing Python
Section 1.1. "And Now for Something Completely Different"
Section 1.2. Python Philosophy 101
Section 1.3. The Life of Python
Section 1.4. Signs of the Python Times
Section 1.5. The Compulsory Features List
Section 1.6. What's Python Good For?
Section 1.7. What's Python Not Good For?
Section 1.8. Truth in Advertising
Chapter 2. A Sneak Preview
Section 2.1. "Programming Python: The Short Story"
Section 2.2. The Task
Section 2.3. Step 1: Representing Records
Section 2.4. Step 2: Storing Records Persistently
Section 2.5. Step 3: Stepping Up to OOP
Section 2.6. Step 4: Adding Console Interaction
Section 2.7. Step 5: Adding a GUI
Section 2.8. Step 6: Adding a Web Interface
Section 2.9. The End of the Demo
Part II: System Programming
Chapter 3. System Tools
Section 3.1. "The os.path to Knowledge"
Section 3.2. System Scripting Overview
Section 3.3. Introducing the sys Module
Section 3.4. Introducing the os Module
Section 3.5. Script Execution Context
Section 3.6. Current Working Directory
Section 3.7. Command-Line Arguments
Section 3.8. Shell Environment Variables
Section 3.9. Standard Streams
Chapter 4. File and Directory Tools
Section 4.1. "Erase Your Hard Drive in Five Easy Steps!"
8.
Section 4.2. FileTools
Section 4.3. Directory Tools
Chapter 5. Parallel System Tools
Section 5.1. "Telling the Monkeys What to Do"
Section 5.2. Forking Processes
Section 5.3. Threads
Section 5.4. Program Exits
Section 5.5. Interprocess Communication
Section 5.6. Pipes
Section 5.7. Signals
Section 5.8. Other Ways to Start Programs
Section 5.9. A Portable Program-Launch Framework
Section 5.10. Other System Tools
Chapter 6. System Examples: Utilities
Section 6.1. "Splits and Joins and Alien Invasions"
Section 6.2. Splitting and Joining Files
Section 6.3. Generating Forward-Link Web Pages
Section 6.4. A Regression Test Script
Section 6.5. Packing and Unpacking Files
Section 6.6. Automated Program Launchers
Chapter 7. System Examples: Directories
Section 7.1. "The Greps of Wrath"
Section 7.2. Fixing DOS Line Ends
Section 7.3. Fixing DOS Filenames
Section 7.4. Searching Directory Trees
Section 7.5. Visitor: Walking Trees Generically
Section 7.6. Copying Directory Trees
Section 7.7. Deleting Directory Trees
Section 7.8. Comparing Directory Trees
Part III: GUI Programming
Chapter 8. Graphical User Interfaces
Section 8.1. "Here's Looking at You, Kid"
Section 8.2. Python GUI Development Options
Section 8.3. Tkinter Overview
Section 8.4. Climbing the GUI Learning Curve
Section 8.5. Tkinter Coding Basics
Section 8.6. Tkinter Coding Alternatives
Section 8.7. Adding Buttons and Callbacks
Section 8.8. Adding User-Defined Callback Handlers
Section 8.9. Adding Multiple Widgets
Section 8.10. Customizing Widgets with Classes
Section 8.11. Reusable GUI Components with Classes
Section 8.12. The End of the Tutorial
Section 8.13. Python/Tkinter for Tcl/Tk Converts
Chapter 9. A Tkinter Tour, Part 1
Section 9.1. "Widgets and Gadgets and GUIs, Oh My!"
Section 9.2. Configuring Widget Appearance
Section 9.3. Top-Level Windows
Section 9.4. Dialogs
Section 9.5. Binding Events
9.
Section 9.6. Messageand Entry
Section 9.7. Checkbutton, Radiobutton, and Scale
Section 9.8. Running GUI Code Three Ways
Section 9.9. Images
Section 9.10. Viewing and Processing Images with PIL
Chapter 10. A Tkinter Tour, Part 2
Section 10.1. "On Today's Menu: Spam, Spam, and Spam"
Section 10.2. Menus
Section 10.3. Listboxes and Scrollbars
Section 10.4. Text
Section 10.5. Canvas
Section 10.6. Grids
Section 10.7. Time Tools, Threads, and Animation
Section 10.8. The End of the Tour
Section 10.9. The PyDemos and PyGadgets Launchers
Chapter 11. GUI Coding Techniques
Section 11.1. "Building a Better Mouse Trap"
Section 11.2. GuiMixin: Common Tool Mixin Classes
Section 11.3. GuiMaker: Automating Menus and Toolbars
Section 11.4. ShellGui: GUIs for Command-Line Tools
Section 11.5. GuiStreams: Redirecting Streams to Widgets
Section 11.6. Reloading Callback Handlers Dynamically
Section 11.7. Wrapping Up Top-Level Window Interfaces
Section 11.8. GUIs, Threads, and Queues
Section 11.9. More Ways to Add GUIs to Non-GUI Code
Chapter 12. Complete GUI Programs
Section 12.1. "Python, Open Source, and Camaros"
Section 12.2. PyEdit: A Text Editor Program/Object
Section 12.3. PyPhoto: An Image Viewer and Resizer
Section 12.4. PyView: An Image and Notes Slideshow
Section 12.5. PyDraw: Painting and Moving Graphics
Section 12.6. PyClock: An Analog/Digital Clock Widget
Section 12.7. PyToe: A Tic-Tac-Toe Game Widget
Section 12.8. Where to Go from Here
Part IV: Internet Programming
Chapter 13. Network Scripting
Section 13.1. "Tune In, Log On, and Drop Out"
Section 13.2. Plumbing the Internet
Section 13.3. Socket Programming
Section 13.4. Handling Multiple Clients
Section 13.5. A Simple Python File Server
Chapter 14. Client-Side Scripting
Section 14.1. "Socket to Me!"
Section 14.2. FTP: Transferring Files over the Net
Section 14.3. Processing Internet Email
Section 14.4. POP: Fetching Email
Section 14.5. SMTP: Sending Email
Section 14.6. email: Parsing and Composing Mails
Section 14.7. pymail: A Console-Based Email Client
Section 14.8. The mailtools Utility Package
10.
Section 14.9. NNTP:Accessing Newsgroups
Section 14.10. HTTP: Accessing Web Sites
Section 14.11. Module urllib Revisited
Section 14.12. Other Client-Side Scripting Options
Chapter 15. The PyMailGUI Client
Section 15.1. "Use the Source, Luke"
Section 15.2. A PyMailGUI Demo
Section 15.3. PyMailGUI Implementation
Chapter 16. Server-Side Scripting
Section 16.1. "Oh What a Tangled Web We Weave"
Section 16.2. What's a Server-Side CGI Script?
Section 16.3. Running Server-Side Examples
Section 16.4. Climbing the CGI Learning Curve
Section 16.5. Saving State Information in CGI Scripts
Section 16.6. The Hello World Selector
Section 16.7. Refactoring Code for Maintainability
Section 16.8. More on HTML and URL Escapes
Section 16.9. Transferring Files to Clients and Servers
Chapter 17. The PyMailCGI Server
Section 17.1. "Things to Do When Visiting Chicago"
Section 17.2. The PyMailCGI Web Site
Section 17.3. The Root Page
Section 17.4. Sending Mail by SMTP
Section 17.5. Reading POP Email
Section 17.6. Processing Fetched Mail
Section 17.7. Utility Modules
Section 17.8. CGI Script Trade-Offs
Chapter 18. Advanced Internet Topics
Section 18.1. "Surfing on the Shoulders of Giants"
Section 18.2. Zope: A Web Application Framework
Section 18.3. HTMLgen: Web Pages from Objects
Section 18.4. Jython: Python for Java
Section 18.5. Grail: A Python-Based Web Browser
Section 18.6. XML Processing Tools
Section 18.7. Windows Web Scripting Extensions
Section 18.8. Python Server Pages
Section 18.9. Rolling Your Own Servers in Python
Section 18.10. And Other Cool Stuff
Part V: Tools and Techniques
Chapter 19. Databases and Persistence
Section 19.1. "Give Me an Order of Persistence, but Hold the Pickles"
Section 19.2. Persistence Options in Python
Section 19.3. DBM Files
Section 19.4. Pickled Objects
Section 19.5. Shelve Files
Section 19.6. The ZODB Object-Oriented Database
Section 19.7. SQL Database Interfaces
Section 19.8. PyForm: A Persistent Object Viewer
Chapter 20. Data Structures
Section 20.1. "Roses Are Red, Violets Are Blue; Lists Are Mutable, and So Is Set Foo"
11.
Section 20.2. ImplementingStacks
Section 20.3. Implementing Sets
Section 20.4. Subclassing Built-In Types
Section 20.5. Binary Search Trees
Section 20.6. Graph Searching
Section 20.7. Reversing Sequences
Section 20.8. Permuting Sequences
Section 20.9. Sorting Sequences
Section 20.10. Data Structures Versus Python Built-Ins
Section 20.11. PyTree: A Generic Tree Object Viewer
Chapter 21. Text and Language
Section 21.1. "See Jack Hack. Hack, Jack, Hack"
Section 21.2. Strategies for Parsing Text in Python
Section 21.3. String Method Utilities
Section 21.4. Regular Expression Pattern Matching
Section 21.5. Advanced Language Tools
Section 21.6. Handcoded Parsers
Section 21.7. PyCalc: A Calculator Program/Object
Part VI: Integration
Chapter 22. Extending Python
Section 22.1. "I Am Lost at C"
Section 22.2. Integration Modes
Section 22.3. C Extensions Overview
Section 22.4. A Simple C Extension Module
Section 22.5. Extension Module Details
Section 22.6. The SWIG Integration Code Generator
Section 22.7. Wrapping C Environment Calls
Section 22.8. A C Extension Module String Stack
Section 22.9. A C Extension Type String Stack
Section 22.10. Wrapping C++ Classes with SWIG
Section 22.11. Other Extending Tools
Chapter 23. Embedding Python
Section 23.1. "Add Python. Mix Well. Repeat."
Section 23.2. C Embedding API Overview
Section 23.3. Basic Embedding Techniques
Section 23.4. Registering Callback Handler Objects
Section 23.5. Using Python Classes in C
Section 23.6. A High-Level Embedding API: ppembed
Section 23.7. Other Integration Topics
Part VIII: The End
Chapter 24. Conclusion: Python and the Development Cycle
Section 24.1. "That's the End of the Book, Now Here's the Meaning of Life"
Section 24.2. "Something's Wrong with the Way We Program Computers"
Section 24.3. The "Gilligan Factor"
Section 24.4. Doing the Right Thing
Section 24.5. Enter Python
Section 24.6. But What About That Bottleneck?
Section 24.7. On Sinking the Titanic
Section 24.8. So What's "Python: The Sequel"?
Section 24.9. In the Final Analysis . . .
12.
Section 24.10. Postscriptto the Second Edition (2000)
Section 24.11. Postscript to the Third Edition (2006)
About the Author
Colophon
Index
Foreword
How Time Flies!
Tenyears ago I completed the foreword for the first edition of this book. Python 1.3 was current
then, and 1.4 was in beta. I wrote about Python's origins and philosophy, and about how its first six
years changed my life. Python was still mostly a one-man show at the time, and I only mentioned
other contributors and the Python community in one paragraph near the end.
Five years later the second edition came out, much improved and quite a bit heftier, and I wrote a
new foreword. Python 2.0 was hot then, and the main topic of the foreword was evolution of the
language. Python 2.0 added a lot of new features, and many were concerned that the pace of change
would be unsustainable for the users of the language. I addressed this by promising feature-by-
feature backward compatibility for several releases and by regulating change through a community
process using Python Enhancement Proposals (PEPs).
By then, Python's development had become truly community-driven, with many developers (besides
myself) having commit privileges into the source tree. This move toward community responsibility
has continued ever since. My own role has become more limited over time, though have not yet been
reduced to playing a purely ceremonial function like that of the Dutch Queen.
Perhaps the biggest change in recent years is the establishment of the Python Software Foundation
(PSF), a non-profit organization that formally owns and manages the rights to the Python source
code and owns the Python trademark. Its board and members (helped by many nonmember
volunteers) also offer many services to the Python community, from the Python.org web site and
mailing lists to the yearly Python Conference. Membership in the PSF is by invitation only, but
donations are always welcome (and tax-deductible, at least in the U.S.).
The PSF does not directly control Python's development; however, the developers don't have to obey
any rules set by the PSF. Rather, it's the other way around: active Python developers make up the
majority of the PSF's membership. This arrangement, together with the open source nature of
Python's source code license, ensures that Python will continue to serve the goals of its users and
developers.
Coming Attractions
What developments can Python users expect to see in the coming years? Python 3000, which is
referred to in the foreword to the second edition as "intentionally vaporware," will see the light of day
after all as Python 3.0. After half a decade of talk, it's finally time to start doing something about it.
I've created a branch of the 2.5 source tree, and, along with a handful of developers, I'm working on
transforming the code base into my vision for Python 3000. At the same time, I'm working with the
community on a detailed definition of Python 3000; there's a new mailing dedicated to Python 3000
and a series of PEPs, starting with PEP 3000.
This work is still in the early stages. Some changes, such as removing classic classes and string
exceptions, adopting Unicode as the only character type, and changing integer division so that 1/2
16.
returns 0.5 insteadof truncating toward zero, have been planned for years. But many other changes
are still being hotly debated, and new features are being proposed almost daily.
I see my own role in this debate as a force of moderation: there are many more good ideas than
could possibly be implemented in the given time, and, taken together, they would change the
language so much that it would be unrecognizable. My goal for Python 3000 is to fix some of my
oldest design mistakes, especially the ones that can't be fixed without breaking backward
compatibility. That alone will be a huge task. For example, a consequence of the choice to use
Unicode everywhere is the need for a total rewrite of the standard I/O library and a new data type to
represent binary ("noncharacter") data, dubbed "bytes."
The biggest potential danger for Python 3000 is that of an "accidental paradigm shift": a change, or
perhaps a small set of changes that weren't considered together, that would unintentionally cause a
huge change to the way people program in Python. For example, adding optional static type checking
to the language could easily have the effect of turning Python into "Java without braces"which is
definitely not what most users would like to see happen! For this reason, I am making it my personal
responsibility to guide the Python 3000 development process. The new language should continue to
represent my own esthetics for language design, not a design-by-committee compromise or a radical
departure from today's Python. And if we don't get everything right, well, there's always Python
4000....
The timeline for 3.0 is roughly as follows: I expect the first alpha release in about a year and the first
production release a year later. I expect that it will then take another year to shake out various
usability issues and get major third-party packages ported, and, finally, another year to gain
widespread user acceptance. So, Mark should have about three to four years before he'll have to
start the next revision of this book.
To learn more about Python 3000 and how we plan to help users convert their code, start by reading
PEP 3000. (To find PEP 3000 online, search for it in Google.)
In the meantime, Python 2.x is not dead yet. Python 2.5 will be released around the same time as
this book (it's in late alpha as I am writing this). Python's normal release cycle produces a new
release every 1218 months. I fully expect version 2.6 to see the light of day while Python 3000 is still
in alpha, and it's likely that 2.7 will be released around the same time as 3.0 (and that more users
will download 2.7 than 3.0). A 2.8 release is quite likely; such a release might back-port certain
Python 3.0 features (while maintaining backward compatibility with 2.7) in order to help users
migrate code. A 2.9 release might happen, depending on demand. But in any case, 2.10 will be right
out!
(If you're not familiar with Python's release culture, releases like 2.4 and 2.5 are referred to as
"major releases." There are also "bug-fix releases," such as 2.4.3. Bug-fix releases are just that: they
fix bugs and, otherwise, maintain strict backward and forward compatibility within the same major
release. Major releases introduce new features and maintain backward compatibility with at least one
or two previous major releases, and, in most cases, many more than that. There's no specific name
for "earth-shattering" releases like 3.0, since they happen so rarely.)
Concluding Remarks
Programming Python was the first or second book on Python ever published, and it's the only one of
the early batch to endure to this day. I thank its author, Mark Lutz, for his unceasing efforts in
keeping the book up-to-date, and its publisher, O'Reilly, for keeping the page count constant for this
edition.
Some of my fondest memories are of the book's first editor, the late Frank Willison. Without Frank's
inspiration and support, the first two editions would never have been. He would be proud of this third
17.
edition.
I must endin a fine tradition, with one of my favorite Monty Python quotes: "Take it away, Eric the
orchestra leader!"
Guido van Rossum
Belmont, California, May 2006
Foreword to the Second Edition (2001)
Less than five years ago, I wrote the Foreword for the first edition of Programming Python. Since
then, the book has changed about as much as the language and the Python community! I no longer
feel the need to defend Python: the statistics and developments listed in Mark's Preface speak for
themselves.
In the past year, Python has made great strides. We released Python 2.0, a big step forward, with
new standard library features such as Unicode and XML support, and several new syntactic
constructs, including augmented assignment: you can now write x += 1 instead of x = x+1. A few
people wondered what the big deal was (answer: instead of x, imagine dict[key] or list[index]),
but overall this was a big hit with those users who were already used to augmented assignment in
other languages.
Less warm was the welcome for the extended print statement, print>>file, a shortcut for printing to
a different file object than standard output. Personally, it's the Python 2.0 feature I use most
frequently, but most people who opened their mouths about it found it an abomination. The
discussion thread on the newsgroup berating this simple language extension was one of the longest
everapart from the never-ending Python versus Perl thread.
Which brings me to the next topic. (No, not Python versus Perl. There are better places to pick a fight
than a Foreword.) I mean the speed of Python's evolution, a topic dear to the heart of the author of
this book. Every time I add a feature to Python, another patch of Mark's hair turns graythere goes
another chapter out of date! Especially the slew of new features added to Python 2.0, which appeared
just as he was working on this second edition, made him worry: what if Python 2.1 added as many
new things? The book would be out of date as soon as it was published!
Relax, Mark. Python will continue to evolve, but I promise that I won't remove things that are in
active use! For example, there was a lot of worry about the string module. Now that string objects
have methods, the string module is mostly redundant. I wish I could declare it obsolete (or
deprecated) to encourage Python programmers to start using string methods instead. But given that
a large majority of existing Python codeeven many standard library modulesimports the string
module, this change is obviously not going to happen overnight. The first likely opportunity to
remove the string module will be when we introduce Python 3000; and even at that point, there will
probably be a string module in the backwards compatibility library for use with old code.
Python 3000?! Yes, that's the nickname for the next generation of the Python interpreter. The name
may be considered a pun on Windows 2000, or a reference to Mystery Science Theater 3000, a
suitably Pythonesque TV show with a cult following. When will Python 3000 be released? Not for a
loooooong timealthough you won't quite have to wait until the year 3000.
Originally, Python 3000 was intended to be a complete rewrite and redesign of the language. It would
allow me to make incompatible changes in order to fix problems with the language design that
weren't solvable in a backwards compatible way. The current plan, however, is that the necessary
changes will be introduced gradually into the current Python 2.x line of development, with a clear
transition path that includes a period of backwards compatibility support.
18.
Take, for example,integer division. In line with C, Python currently defines x/y with two integer
arguments to have an integer result. In other words, 1/2 yields 0! While most dyed-in-the-wool
programmers expect this, it's a continuing source of confusion for newbies, who make up an ever-
larger fraction of the (exponentially growing) Python user population. From a numerical perspective,
it really makes more sense for the / operator to yield the same value regardless of the type of the
operands: after all, that's what all other numeric operators do. But we can't simply change Python so
that 1/2 yields 0.5, because (like removing the string module) it would break too much existing code.
What to do?
The solution, too complex to describe here in detail, will have to span several Python releases, and
involves gradually increasing pressure on Python programmers (first through documentation, then
through deprecation warnings, and eventually through errors) to change their code. By the way, a
framework for issuing warnings will be introduced as part of Python 2.1. Sorry, Mark!
So don't expect the announcement of the release of Python 3000 any time soon. Instead, one day
you may find that you are already using Python 3000only it won't be called that, but rather
something like Python 2.8.7. And most of what you've learned in this book will still apply! Still, in the
meantime, references to Python 3000 will abound; just know that this is intentionally vaporware in
the purest sense of the word. Rather than worry about Python 3000, continue to use and learn more
about the Python version that you do have.
I'd like to say a few words about Python's current development model. Until early 2000, there were
hundreds of contributors to Python, but essentially all contributions had to go through my inbox. To
propose a change to Python, you would mail me a context diff, which I would apply to my work
version of Python, and if I liked it, I would check it into my CVS source tree. (CVS is a source code
version management system, and the subject of several books.) Bug reports followed the same path,
except I also ended up having to come up with the patch. Clearly, with the increasing number of
contributions, my inbox became a bottleneck. What to do?
Fortunately, Python wasn't the only open source project with this problem, and a few smart people at
VA Linux came up with a solution: SourceForge! This is a dynamic web site with a complete set of
distributed project management tools available: a public CVS repository, mailing lists (using Mailman,
a very popular Python application!), discussion forums, bug and patch managers, and a download
area, all made available to any open source project for the asking.
We currently have a development group of 30 volunteers with SourceForge checkin privileges, and a
development mailing list comprising twice as many folks. The privileged volunteers have all sworn
their allegiance to the BDFL (Benevolent Dictator For Lifethat's me :-). Introduction of major new
features is regulated via a lightweight system of proposals and feedback called Python Enhancement
Proposals (PEPs). Our PEP system proved so successful that it was copied almost verbatim by the Tcl
community when they made a similar transition from Cathedral to Bazaar.
So, it is with confidence in Python's future that I give the floor to Mark Lutz. Excellent job, Mark. And
to finish with my favorite Monty Python quote: Take it away, Eric, the orchestra leader!
Guido van Rossum
Reston, Virginia, January 2001
Foreword from the First Edition (1996)
As Python's creator, I'd like to say a few words about its origins, adding a bit of personal philosophy.
Over six years ago, in December 1989, I was looking for a "hobby" programming project that would
keep me occupied during the week around Christmas. My office (a government-run research lab in
19.
Amsterdam) would beclosed, but I had a home computer, and not much else on my hands. I
decided to write an interpreter for the new scripting language I had been thinking about lately: a
descendant of ABC that would appeal to UNIX/C hackers. I chose Python as a working title for the
project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus).
Today, I can safely say that Python has changed my life. I have moved to a different continent. I
spend my working days developing large systems in Python, when I'm not hacking on Python or
answering Python-related email. There are Python T-shirts, workshops, mailing lists, a newsgroup,
and now a book. Frankly, my only unfulfilled wish right now is to have my picture on the front page
of the New York Times. But before I get carried away daydreaming, here are a few tidbits from
Python's past.
It all started with ABC, a wonderful teaching language that I had helped create in the early eighties.
It was an incredibly elegant and powerful language aimed at nonprofessional programmers. Despite
all its elegance and power and the availability of a free implementation, ABC never became popular in
the UNIX/C world. I can only speculate about the reasons, but here's a likely one: the difficulty of
adding new "primitive" operations to ABC. It was a monolithic closed system, with only the most
basic I/O operations: read a string from the console, write a string to the console. I decided not to
repeat this mistake in Python.
Besides this intention, I had a number of other ideas for a language that improved upon ABC, and
was eager to try them out. For instance, ABC's powerful data types turned out to be less efficient
than we hoped. There was too much emphasis on theoretically optimal algorithms, and not enough
tuning for common cases. I also felt that some of ABC's features, aimed at novice programmers,
were less desirable for the (then!) intended audience of experienced UNIX/C programmers. For
instance: ABC's idiosyncratic syntax (all uppercase keywords!), some terminology (for example,
"how-to" instead of "procedure"); and the integrated structured editor, which its users almost
universally hated. Python would rely more on the UNIX infrastructure and conventions, without being
UNIX-bound. And in fact, the first implementation was done on a Macintosh.
As it turned out, Python is remarkably free from many of the hang-ups of conventional programming
languages. This is perhaps due to my choice of examples: besides ABC, my main influence was
Modula-3. This is another language with remarkable elegance and power, designed by a small,
strong-willed team (most of whom I had met during a summer internship at DEC's Systems Research
Center in Palo Alto). Imagine what Python would have looked like if I had modeled it after the UNIX
shell and C instead! (Yes, I borrowed from C too, but only its least controversial features, in my
desire to please the UNIX/C audience.)
Any individual creation has its idiosyncracies, and occasionally its creator has to justify them. Perhaps
Python's most controversial feature is its use of indentation for statement grouping, which derives
directly from ABC. It is one of the language's features that is dearest to my heart. It makes Python
code more readable in two ways. First, the use of indentation reduces visual clutter and makes
programs shorter, thus reducing the attention span needed to take in a basic unit of code. Second, it
allows the programmer less freedom in formatting, thereby enabling a more uniform style, which
makes it easier to read someone else's code. (Compare, for instance, the three or four different
conventions for the placement of braces in C, each with strong proponents.)
This emphasis on readability is no accident. As an object-oriented language, Python aims to
encourage the creation of reusable code. Even if we all wrote perfect documentation all of the time,
code can hardly be considered reusable if it's not readable. Many of Python's features, in addition to
its use of indentation, conspire to make Python code highly readable. This reflects the philosophy of
ABC, which was intended to teach programming in its purest form, and therefore placed a high value
on clarity.
Readability is often enhanced by reducing unnecessary variability. When possible, there's a single,
obvious way to code a particular construct. This reduces the number of choices facing the
programmer who is writing the code, and increases the chance that it will appear familiar to a second
20.
programmer reading it.Yet another contribution to Python's readability is the choice to use
punctuation mostly in a conservative, conventional manner. Most operator symbols are familiar to
anyone with even a vague recollection of high school math, and no new meanings have to be learned
for comic strip curse characters like @&$!.
I will gladly admit that Python is not the fastest running scripting language. It is a good runner-up,
though. With ever-increasing hardware speed, the accumulated running time of a program during its
lifetime is often negligible compared to the programmer time needed to write and debug it. This, of
course, is where the real time savings can be made. While this is hard to assess objectively, Python
is considered a winner in coding time by most programmers who have tried it. In addition, many
consider using Python a pleasurea better recommendation is hard to imagine.
I am solely responsible for Python's strengths and shortcomings, even when some of the code has
been written by others. However, its success is the product of a community, starting with Python's
early adopters who picked it up when I first published it on the Net, and who spread the word about
it in their own environment. They sent me their praise, criticism, feature requests, code
contributions, and personal revelations via email. They were willing to discuss every aspect of Python
in the mailing list that I soon set up, and to educate me or nudge me in the right direction where my
initial intuition failed me. There have been too many contributors to thank individually. I'll make one
exception, however: this book's author was one of Python's early adopters and evangelists. With this
book's publication, his longstanding wish (and mine!) of having a more accessible description of
Python than the standard set of manuals, has been fulfilled.
But enough rambling. I highly recommend this book to anyone interested in learning Python, whether
for personal improvement or as a career enhancement. Take it away, Eric, the orchestra leader! (If
you don't understand this last sentence, you haven't watched enough Monty Python reruns.)
Guido van Rossum
Reston, Virginia, May 1996
21.
Preface
"And Now forSomething Completely Different . . . Again"
This book teaches application-level programming with Python. That is, it is about what you can do
with the language once you've mastered its fundamentals.
By reading this book, you will learn to use Python in some of its most common roles: to build GUIs,
web sites, networked tools, scripting interfaces, system administration programs, database and text
processing utilities, and more.
Along the way, you will also learn how to use the Python language in realistically scaled
programsconcepts such as object-oriented programming (OOP) and code reuse are recurring side
themes throughout this text. And you will gain enough information to further explore the application
domains introduced in the book, as well as to explore others.
About This Book
Now that I've told you what this book is, I should tell you what it is not. First of all, this book is not a
reference manual. Although the index can be used to hunt for information, this text is not a dry
collection of facts; it is designed to be read. And while many larger examples are presented along the
way, this book is also not just a collection of minimally documented code samples.
Rather, this book is a tutorial that teaches the most common Python application domains from the
ground up. It covers each of Python's target domains gradually, beginning with in-depth discussions
of core concepts in each domain, before progressing toward complete programs. Large examples do
appear, but only after you've learned enough to understand their techniques and code.
For example, network scripting begins with coverage of network basics and protocols and progresses
through sockets, client-side tools, HTML and CGI fundamentals, and web frameworks. GUI
programming gets a similarly gentle presentation, with one introductory and two tutorial chapters,
before reaching larger, complete programs. And system interfaces are explored carefully before
being applied in real and useful scripts.
In a sense, this book is to application-level programming what the book Learning Python is to the
core Python languagea learning resource that makes no assumptions about your prior experience in
the domains it covers. Because of this focus, this book is designed to be a natural follow-up to the
core language material in Learning Python and a next step on the way to mastering the many facets
of Python programming.
In deference to all the topic suggestions I have received over the years, I should also point out that
this book is not intended to be an in-depth look at specific systems or tools. With perhaps one million
Python users in the world today, it would be impossible to cover in a useful way every Python-related
system that is of interest to users.
Instead, this book is designed as a tutorial for readers new to the application domains covered. The
web chapters, for instance, focus on core web scripting ideas, such as server-side scripts and state
22.
retention options, noton specific systems, such as SOAP, Twisted, and Plone. By reading this book,
you will gain the groundwork necessary to move on to more specific tools such as these in the
domains that interest you.
About This Edition
To some extent, this edition's structure is a result of this book's history. The first edition of this book,
written in 1995 and 1996, was the first book project to present the Python language. Its focus was
broad. It covered the core Python language, and it briefly introduced selected application domains.
Over time, the core language and reference material in the first edition evolved into more focused
books Learning Python and Python Pocket Reference.
Given that evolution, the second edition of this book, written from 1999 to 2000, was an almost
completely new book on advanced Python topics. Its content was an expanded and more complete
version of the first edition's application domain material, designed to be an application-level follow-up
to the core language material in Learning Python, and supplemented by the reference material in
Python Pocket Reference. The second edition focused on application libraries and tools rather than on
the Python language itself, and it was oriented toward the practical needs of real developers and real
tasksGUIs, web sites, databases, text processing, and so on.
This third edition, which I wrote in 2005 and 2006, is exactly like the second in its scope and focus,
but it has been updated to reflect Python version 2.4, and to be compatible with the upcoming
Python 2.5. It is a minor update, and it retains the second edition's design and scope as well as much
of its original material. However, its code and descriptions have been updated to incorporate both
recent changes in the Python language, as well as current best practices in Python programming.
Python Changes
You'll find that new language features such as string methods, enclosing-function scope references,
list comprehensions, and new standard library tools, such as the email package, have been
integrated throughout this edition. Smaller code changesfor instance, replacing apply calls and
exc_type usage with the newer func(*args) and exc_info( )have been applied globally as well (and
show up surprisingly often, because this book is concerned with building general tools).
All string-based, user-defined exceptions are now class-based, too; string exceptions appeared half a
dozen times in the book's examples, but are documented as deprecated today. This is usually just a
matter of changing to class MyExc(Exception): pass, though, in one case, exception constructor
arguments must be extracted manually with the instance's args attribute. 'X' also became repr(X)
across all examples, and I've replaced some appearances of while 1: with the newer and more
mnemonic while True:, though either form works as advertised and C programmers often find the
former a natural pattern. Hopefully, these changes will future-proof the examples for as long as
possible; be sure to watch the updates page described later for future Python changes.
One futurisms note: some purists might notice that I have not made all classes in this book derive
from object to turn on new-style class features (e.g., class MyClass(object)). This is partly because
the programs here don't employ the new-style model's slightly modified search pattern or advanced
extensions. This is also because Python's creator, Guido van Rossum, told me that he believes this
derivation will not be required in Python 3.0standalone classes will simply be new-style too,
automatically (in fact, the new-style class distinction is really just a temporary regression due to its
incompatible search order in particular rare, multiple-inheritance trees). This is impossible to predict
with certainty, of course, and Python 3.0 might abandon compatibility in other ways that break some
examples in this book. Be sure to both watch for 3.0 release notes and keep an eye on this book's
updates page over time.
23.
Example Changes
You'll alsonotice that many of the second edition's larger examples have been upgraded
substantially, especially the two larger GUI and CGI email-based examples (which are arguably the
implicit goals of much of the book). For instance:
The PyMailGUI email client is a complete rewrite and now supports sending and receiving
attachments, offline viewing from mail save files, true transfer thread overlap, header-only
fetches and mail caches, auto-open of attachments, detection of server inbox message number
synchronization errors, and more.
The PyMailCGI email web site was also augmented to support sending and receiving mail
attachments, locate an email's main text intelligently, minimize mail fetches to run more
efficiently, and use the PyCrypto extension for password encryption.
The PyEdit text editor has grown a font dialog; unlimited undo and redo; a configuration module
for fonts, colors, and sizes; intelligent modified tests on quit, open, new, and run; and case-
insensitive searches.
PyPhoto, a new, major example in Chapter 12, implements an image viewer GUI with Tkinter
and the optional PIL extension. It supports cached image thumbnails, image resizing, saving
images to files, and a variety of image formats thanks to PIL.
PyClock has incorporated a countdown timer and a custom window icon; PyCalc has various
cosmetic and functionality upgrades; and PyDemos now automatically pops up examples'
source files.
In addition to the enhanced and new, major examples, you'll also find many other examples that
demonstrate new and advanced topics such as thread queues.
Topic Changes
In addition to example changes, new topics have been added throughout. Among these are the
following:
Part II, System Programming, looks at the struct, mimetools, and StringIO modules and has
been updated for newer tools such as file iterators.
Part III, GUI Programming, has fresh coverage of threading and queues, the PIL imaging
library, and techniques for linking a separately spawned GUI with pipes and sockets.
Part IV, Internet Programming, now uses the new email package; covers running a web server
on your local machine for CGI scripts; has substantially more on cookies, Zope, and XML
parsing; and uses the PyCrypto encryption toolkit.
Chapter 19, Databases and Persistence, has new ZODB examples and much-expanded coverage
of the SQL API, including dozens of new pages on using MySQL and ZODB.
Chapter 21, Text and Language, has a new, gentler introduction to pattern matching and
mentions Python 2.4 templates.
24.
Chapter 22, ExtendingPython, now introduces Distutils and includes overviews of Pyrex, SIP,
ctypes, Boost.Python, and CXX, in addition to offering updated SWIG coverage.
Beyond these specific kinds of changes, some material has been reorganized to simplify the overall
structure. For example, a few chapters have been split up to make them less challenging; appendixes
have been removed to save space (references are available separately); and the PyErrata web site
example chapter has been removed (it didn't present many new concepts, so we've made it and its
code available in the book's examples distribution as optional reading).
You'll also find a new "Sneak Preview" chapter for readers in a hurrya throwback to the first edition.
This chapter takes a single example from command line to GUI to web site, and introduces Python
and its libraries along the way.
Focus Unchanged
Fundamentally, though, this edition, like the second, is still focused on ways to use Python rather
than on the language itself. Python development concepts are explored along the wayin fact, they
really become meaningful only in the context of larger examples like those in this edition. Code
structure and reuse, for instance, are put into practice by refactoring and reusing examples
throughout the book.
But in general, this text assumes that you already have at least a passing acquaintance with Python
language fundamentals, and it moves on to present the rest of the Python storyits application to real
tasks. If you find code in this book confusing, I encourage you to read Learning Python as a prelude
to this text.
In the remainder of this preface, I'll explain some of the rationales for this design, describe the
structure of this edition in more detail, and give a brief overview of how to use the Python programs
shipped in the book examples package.
This Book's Motivation
Over the 10 years since the first edition of this book was written, Python has transitioned from an
emerging language that was of interest primarily to pioneers to a widely accepted tool used by
programmers for day-to-day development tasks. Along the way, the Python audience has changed as
well, and this book has been refocused with this new readership in mind. You will find that it is a
nuts-and-bolts text, geared less toward introducing and popularizing the language and more toward
showing you how to apply Python for realistically scaled programming tasks.
25.
So, What's Python?
Ifyou are looking for a concise definition of this book's topic, try this:
Python is a general-purpose, open source computer programming language optimized for
quality, productivity, portability, and integration. It is used by hundreds of thousands of
developers around the world in areas such as Internet scripting, systems programming,
user interfaces, product customization, and more.
As a popular programming language that shrinks the development time, Python is used
in a wide variety of products and roles. Counted among its current user base are Google,
Industrial Light & Magic, ESRI, the BitTorrent file sharing system, NASA's Jet Propulsion
Lab, and the U.S. National Weather Service. Python's application domains range from
system administration, web site development, cell phone scripting, and education to
hardware testing, investment analysis, computer games, and spacecraft control.
Among other things, Python sports OOP; a remarkably simple, readable, and
maintainable syntax; integration with C components; and a vast collection of precoded
interfaces and utilities. Its tool set makes it a flexible and agile language, ideal for both
quick tactical tasks as well as longer-range strategic application development efforts.
Although it is a general-purpose language, Python is often called a scripting language
because it makes it easy to utilize and direct other software components. Perhaps
Python's best asset is simply that it makes software development more rapid and
enjoyable. To truly understand how, read on; we'll expand on these concepts in the next
chapter.
Since writing the first edition, I have also had the opportunity to teach Python classes in the U.S. and
abroad some 170 times as of mid-2006, and this book reflects feedback garnered from these training
sessions. The application domain examples, for instance, reflect interests and queries common
among the thousands of students I have introduced to Python. Teaching Python to workers in the
trenches, many of whom are now compelled to use Python on the job, also inspired a new level of
practicality that you will notice in this book's examples and topics.
Other book examples are simply the result of me having fun programming Python. Yes, fun. One of
the most common remarks I hear from Python newcomers is that Python is actually enjoyable to
useit is able to both kindle the excitement of programming among beginners and rekindle that
excitement among those who have toiled for years with more demanding tools. When you can code
as fast as you can think, programming becomes a very different proposition and feels more like
pleasure than work.
As you will see in this book, Python makes it easy to play with advanced but practical tools such as
threads, sockets, GUIs, web sites, and OOPareas that can be both tedious and daunting in traditional
languages such as C and C++. It enables things you may not have considered or attempted with
other tools.
Frankly, even after 14 years as a bona fide Pythonista, I still find programming most enjoyable when
I do it in Python. Python is a remarkably productive and flexible language, and witnessing its
application firsthand is an aesthetic pleasure. I hope this edition, as much as the two before it, will
both demonstrate how to reap Python's productivity benefits and communicate some of the
excitement to be found in this rewarding tool.
26.
This Book's Structure
Althoughcode examples are reused throughout the book and later chapters build upon material in
earlier chapters (e.g., GUIs), topics in this book are covered fairly independently and are grouped
together in different parts. If a particular domain's part doesn't interest you, you can generally skip
ahead to a part that does.
As a result, it's not too much of a stretch to consider this edition as akin to four or five books in one.
Its top-level structure underscores its application-topics focus (see the Table of Contents for a more
fine-grained look at the book's structure):
Part I, The Beginning
I start off with an overview of some of the main ideas behind Python and a quick sneak-
preview chapter to whet your appetite. The sneak preview doesn't teach much, but it serves as
an introduction and demo for some of the topics to come, and as a refresher for core Python
concepts such as OOP.
Part II, System Programming
This section explores the system-level interfaces in Python as well as their realistic applications.
We'll look at topics such as threading, directory walkers, processes, environment variables, and
streams, and we will apply such tools to common system administration tasks such as directory
searchers and file splitters.
Part III, GUI Programming
In this section, you'll learn how to build portable GUIs with Python. The Tkinter toolkit is
covered from the ground up as you move from basics to techniques to constructing complete
programs. You'll build text editors, clocks, and more in this part. GUIs also show up throughout
the rest of the book, and they often reuse some of the tools you'll build here.
Part IV, Internet Programming
In this section, you'll learn all about using Python on the Internet. I begin with network basics
and sockets, move through client-side tools like FTP and email, and end up using server-side
tools to implement interactive web sites. Along the way, I'll contrast different ways to move
bits around the Web with Python. You'll code GUI and web-based email programs, for example,
to help underscore trade-offs between client- and server-side techniques. A final chapter in this
part surveys more advanced toolkits and techniques for Internet-related application
developmentZope, Jython, XML, and the like.
Part V, Tools and Techniques
This part is a collection of tool topics that span application domainsdatabase interfaces and
object persistence, text and language processing, and data structure implementation. You'll
build GUIs here for browsing databases, viewing data structures, and performing calculations.
Part VI, Integration
27.
This part ofthe book looks at the interfaces available for mixing Python with programs written
in C and C++. These interfaces allow Python to script existing libraries and to serve as an
embedded customization tool. As you'll see, by combining Python with compiled languages,
programs can be both flexible and efficient.
Part VII, The End
Finally, I'll wrap up with a conclusion that looks at some of the implications of Python's
scripting role.
Two notes about the structure: first of all, don't let these titles fool youalthough most have to do with
application topics, Python language features and general design concepts are still explored along the
way, in the context of real-world goals. Secondly, readers who use Python as a standalone tool can
safely skip the integration part, though I still recommend a quick glance. C programming isn't nearly
as fun or as easy as Python programming is. Yet, because integration is central to Python's role as a
scripting tool, a cursory understanding can be useful, regardless of whether you do integrating,
scripting, or both.
This Edition's Design
The best way to get a feel for any book is to read it, of course. But especially for people who are
familiar with the prior edition, this section will clarify regarding what is new this time around.
It's Been Updated for Python 2.4 (and 2.5)
All of the example code has been upgraded to use the latest features of the Python language and its
standard library. Python is still largely compatible with the code in the first two editions, but recent
language additions such as nested scopes and list comprehensions simplify many coding tasks. For
instance, default arguments are no longer required to pass objects into most lambda expressions,
and the new email package greatly simplifies the tasks of parsing and adding email attachments. See
the Python changes list earlier in this chapter for more on this subject.
Although the GUI examples in this book required almost no code changes, they have been updated to
run on Tk 8.4, the library used by Python 2.4 as its standard portable GUI toolkit. Among other
things, the latest Tk allows window icons to be set by the program. Although begun under 2.4, this
edition is also compatible with the upcoming Python 2.5 release.
It's Been Reorganized
A few chapters have been moved to make the flow more logical; for example, the sections on files
and directories and the PyMailGUI example are now in chapters of their own. In addition, all
appendixes were cut (this book is neither a reference nor a Python changes log), and a new initial
preview chapter was added to introduce topics explored throughout the book.
As mentioned earlier, in deference to space, one second-edition chapterthat on the PyErrata web
sitehas been cut in this edition. Its main, unique topics on state retention have been incorporated
into other chapters. The original source code for the PyErrata site still appears on the book's
examples package, as supplemental reading.[*]
28.
[*] I regretcutting this chapter, but new material was added, and as you can tell, this is already a substantial book. As my first editor,
Frank Willison, famously said when the second edition came out, if this book were run over by a truck, it would do damage....
It Covers New Topics
You'll find much-expanded coverage of Zope, the ZODB database, threading tools and techniques
including the queue module, SQL interfaces, XML parsing, and more. See the example and topic
changes lists provided earlier for additional details. Most of the new or expanded topics are a result of
the evolution of common practice in the Python world. While this book doesn't address core language
evolution directly (the basics of new language tools such as list comprehensions are the domain of
the text Learning Python), it does employ it throughout its examples.
It's Still Mostly Platform-Neutral
Except for some C integration examples, the majority of the programs in this edition were developed
on Windows XP computers, with an eye toward portability to Linux and other platforms. In fact, some
of the examples were born of my desire to provide portable Python equivalents of tools missing on
Windows (e.g., file splitters). When programs are shown in action, it's usually on Windows; they are
demonstrated on the Linux platform only if they exercise Unix-specific interfaces.
This is not meant as a political statement; it is mostly a function of the fact that I wrote this book
with Microsoft Word. When time is tight, it's more convenient to run scripts on the same platform as
your publishing tools than to frequently switch platforms. Luckily, because Python has become so
portable, the underlying operating system is largely irrelevant to developers. Python, its libraries, and
its Tkinter GUI framework work extremely well on all major platforms today.
Where platform issues do come into play, though, I've made the examples as platform-neutral as
possible, and I point out platform-specific issues along the way. Generally speaking, most of the
scripts should work unchanged on common Python platforms. For instance, all the GUI examples
were tested on both Windows (ME, XP) and Linux (KDE, Gnome), and most of the command-line and
thread examples were developed on Windows but work on Linux too. Because Python's system
interfaces are built to be portable, this is easier than it may sound; it's largely automatic.
On the other hand, this book does delve into platform-specific topics where appropriate. For instance,
there is coverage of many Windows-specific topicsActive Scripting, COM, program launch options,
and so on. Linux and Unix readers will also find material geared toward their platformsforks, pipes,
and the like.
C integration code platform issues
The one place where readers may still catch a glimpse of platform biases is in the Python/C
integration examples. For simplicity, the C compilation details covered in this text are still somewhat
Unix/Linux-oriented. One can make a reasonable case for such a focusnot only does Linux come with
C compilers, but the Unix development environment it provides grew up around that language. On
standard Windows, the C code shown in this book will work, but you may need to use different build
procedures (they vary per Windows compiler, some of which are very similar to Linux compilers).
In fact, for this third edition of the book, many of the C integration examples were run on the Cygwin
system, not on Linux. Cygwin provides a complete, Unix-like environment and library for Windows. It
includes C development tools, command-line utilities, and a version of Python that supports Unix
tools not present in the standard Windows Python, including process forks and fifos. Unlike Linux,
because it runs on Windows, Cygwin does not require a complete operating system installation (see
29.
http://www.cygwin.com).
Cygwin has aGPL-style, open source license that requires giving away code (more on this later in the
book). If you do not wish to download and install Cygwin, you may have to translate some of the C
integration build files for your platform; the standard C development concepts apply. On standard
Windows, you'll have to translate for your C compiler. O'Reilly has published an outstanding text,
Python Programming on Win32, that covers Windows-specific Python topics like this, and it should
help address any disparity you may find here.
It's Still Focused for a More Advanced Audience
Becoming proficient in Python involves two distinct tasks: learning the core language itself, and then
learning how to apply it in applications. This book addresses the latter (and larger) of these tasks by
presenting Python libraries, tools, and programming techniques.
Learning Python syntax and datatypes is an important first step, and a prerequisite to this book. Very
soon after you've learned how to slice a list, though, you'll find yourself wanting to do real things, like
writing scripts to compare file directories, responding to user requests on the Internet, displaying
images in a window, reading email, and so on. Most of the day-to-day action is in applying the
language, not the language itself.
That's what this book is for. It covers libraries and tools beyond the core language, which become
paramount when you begin writing real applications. It also addresses larger software design issues
such as reusability and OOP, which can be illustrated only in the context of realistically scaled
programs. Because it assumes you already know Python, this is a somewhat advanced text; again, if
you find yourself lost, you might do well to learn the core language from other resources before
returning here.
It's Still Example-Oriented
Although this book teaches concepts before applying them, it still contains many larger working
programs that tie together concepts presented earlier in the book and demonstrate how to use
Python for realistically scaled tasks. Among them:
PyEdit
A Python/Tk text-file editor object and program
PyView
A photo image and note-file slideshow
PyDraw
A paint program for drawing and moving image objects
PyTree
30.
A tree datastructure drawing program
PyClock
A Python/Tk analog and digital clock widget
PyToe
An AI-powered graphical tic-tac-toe program
PyForm
A persistent object table browser
PyCalc
A calculator widget in Python/Tk
PyMailGUI
A Python/Tkinter POP and SMTP email client
PyFtp
A simple Python/Tk file-transfer GUI
PyMailCGI
A web-based email client interface
PyPhoto
A new thumbnail picture viewer with resizing and saves
See the earlier example changes list for more about how some of these have mutated in this edition.
Besides the major examples listed here, there are also mixed-mode C integration examples (e.g.,
callback registration and class object processing); SWIG examples (with and without "shadow"
classes for C++); more Internet examples (FTP upload and download scripts, NNTP and HTTP
examples, email tools, and socket and select module examples); many examples of Python threads
and thread queues; and coverage of Jython, HTMLgen, Zope, COM, XML parsing, and Python ZODB
and MySQL database interfaces. In addition, as mentioned earlier, the second edition's PyErrata web
site example appears in the examples distribution.
31.
But It's StillNot a Reference Manual
This edition, like the first, is still more of a tutorial than a reference manual (despite
sharing a title pattern with a popular Perl reference text). This book aims to teach, not to
document. You can use its table of contents and index to track down specifics, and the
new structure helps make this easy to do. But this edition is still designed to be used in
conjunction with, rather than to replace, Python reference manuals. Because Python's
manuals are free, well written, available online, and change frequently, it would be folly
to devote space to parroting their content. For an exhaustive list of all tools available in
the Python system, consult other books (e.g., O'Reilly's Python Pocket Reference and
Python in a Nutshell) or the standard manuals at Python's web site (see
http://www.python.org/doc).
Using the Book's Examples
Because examples are central to the structure of this book, I want to briefly describe how to use
them here. In general, though, see the following text files in the examples directory for more details:
README-root.txt
Package structure notes
PP3EREADME-PP3E.txt
General usage notes
Of these, the README-PP3E.txt file is the most informative. In addition, the PP3EConfig directory
contains low-level configuration file examples for Windows and Linux, which may or may not be
applicable to your usage. I give an overview of some setup details here, but the preceding files give
the complete description.
The Book Examples Tree
In a sense, the directory containing the book's examples is itself a fairly sophisticated Python
software system and the examples within it have been upgraded structurally in a number of
important ways:
Examples directory tree: a package
The entire examples distribution has been organized as one Python module package to facilitate
cross-directory imports and avoid name clashes with other Python code installed on your
computer. All cross-directory imports in book examples are package imports, relative to the
examples root directory.
32.
Using directory pathsin import statements (instead of a complex PYTHONPATH) also tends to
make it easier to tell where modules come from. Moreover, you now need to add only one
directory to your PYTHONPATH search-path setting for the entire book examples tree: the
directory containing the PP3E examples root directory. To reuse code in this book within your
own applications, simply import through the PP3E package root (e.g., from PP3E.Launcher
import which, or import PP3E.Gui.Tools.threadtools).
Example filenames
Module names are now descriptive and of arbitrary length (I punted on 8.3 DOS compatibility
long ago), and any remaining all-uppercase filenames are long gone.
Example listing titles
Labels of example listings give the full directory pathname of the example's source file to help
you locate it in the examples distribution. For instance, an example source-code file whose
name is given as Example N-M: PP3EInternetFtpsousa.py refers to the file sousa.py in the
PP3EInternetFtp subdirectory of the examples directory. The examples directory is the
directory containing the top-level PP3E directory of the book examples tree. The examples tree
is simply the Examples directory of the book examples distribution, described further in the
next section.
Example command lines
Similarly, command lines give their directory context. For example, when a command line is
shown typed after a system prompt, as in ...PP3ESystemStreams>, it is really to be typed at
a system command-line prompt, while working in the PP3ESystemStreams subdirectory in
your examples directory. Unix and Linux users: think / when you see in filename paths.
Example launchers
Because it's just plain fun to click on things right away, there are also self-configuring demo
launcher programs (described later), to give you a quick look at Python scripts in action with
minimal configuration requirements. You can generally run them straight from the examples
package without any configuration.
The Book Examples Distribution Package
You can find the book examples distribution package on the book's web page at O'Reilly's web site,
http://www.oreilly.com/catalog/python3/. The book examples directory is located in the PP3E
subdirectory of the topmost Examples directory in the packagethat is, ExamplesPP3E on Windows
and Examples/PP3E on Linux.
If you've copied the examples to your machine, the examples directory is wherever you copied the
PP3E root directory. Example titles reflect this tree's structure. For instance, an example title of
PP3EPreviewmod.py refers to the ExamplesPP3EPreviewmod.py file at the top level of the book
examples distribution package.
You can run most of the examples from within the package directly, but if you obtained them on a
CD, you'll want to copy them to a writable medium such as your hard drive to make changes, and to
allow Python to save .pyc compiled bytecode files for quicker startups. See the example package's
33.
top-level README filefor more details, or browse the examples directory in your favorite file explorer
for a quick tour.
Depending on how often the book's distribution package is maintained, it may also contain extra
open source packages such as the latest releases of Python, the SWIG code generator, and Windows
extensions, but you can always find up-to-date releases of Python and other packages on the Web
(see Python's web site, http://www.python.org, or search the Web). In fact, you shouldmost likely,
the Web will very quickly become more current than any extra software included in the book's
package.
Running Examples: The Short Story
Now the fun stuffif you want to see some Python examples right away, do this:
Install Python from the book's distribution package or from Python's web site
(http://www.python.org), unless it is already present on your computer. If you use a Linux or
recent Macintosh, Python is probably already installed. On Windows, click on the name of the
Python self-installer program and do a default install (click Yes or Next in response to every
prompt). On other systems, see the README file.
1.
Start one of the following self-configuring scripts located in the top-level ExamplesPP3E
directory of the book examples package. Either click on their icons in your file explorer, or run
them from your system prompt (e.g., a Windows console box, or Linux xterm) using command
lines of the form python scriptname (you may need to use the full path to python if it's not
implicit on your system):
Launch_PyDemos.pyw
The main Python/Tk demo launcher toolbar
Launch_PyGadgets_bar.pyw
A Python/Tk utilities launcher bar
Launch_PyGadgets.py
Starts the standard Python/Tk utilities
LaunchBrowser.py
Opens the web examples index page in your web browser
2.
The Launch_* scripts start Python programs portably[*] and require only that Python be installedyou
don't need to set any environment variables first to run them. LaunchBrowser will work if it can find a
web browser on your machine even if you don't have an Internet link (though some Internet
examples won't work completely without a live link).
[*] All the demo and launcher scripts are written portably but are known to work only on Windows and Linux at the time of this writing;
they may require minor changes on other platforms. Apologies if you're using a platform that I could not test: Tk runs on Windows,
X Windows, and Macs; Python itself runs on everything from PDAs, iPods, and cell phones to real-time systems, mainframes, and
34.
supercomputers; and myadvance for writing this book wasn't as big as you may think.
The demo launchers also include a number of web-based programs that use a web browser for their
interface. When run, these programs launch a locally running web server coded in Python (we'll meet
this server script later in this book). Although these programs can run on a remote server too, they
still require a local Python installation to be used with a server running on your machine.
Running Examples: The Details
This section goes into a few additional details about running the book's example programs. If you're
in a hurry, feel free to skip this and run the programs yourself now.
Demos and gadgets
To help organize the book's examples, I've provided a demo launcher program GUI, PyDemos2.pyw,
in the top-level PP3E directory of the examples distribution. Figure P-1 shows PyDemos in action on
Windows after pressing a few buttons. We'll meet in this text all the programs shown in the figure.
The launcher bar itself appears on the top right of the screen; with it, you can run most of the major
graphical examples in the book with a mouse click, and view their source code in pop-up windows.
The demo launcher bar can also be used to start major Internet book examples if a browser can be
located on your machine and a Python-coded server can be started.
Figure P-1. The PyDemos launcher with gadgets and demos
35.
Besides launching demos,the PyDemos source code provides pointers to major examples in the
examples tree; see its code for details. You'll also find automated build scripts for the Python/C
integration examples in the Integration examples directory, which serve as indexes to major C
examples.
I've also included a top-level program called PyGadgets.py, and its relative, PyGadgets_bar.pyw, to
launch some of the more useful GUI book examples for real use instead of demonstration (mostly,
the programs I use; configure as desired). Run PyGadgets_bar to see how it looksit's a simple row of
buttons that pop up many of the same programs shown in Figure P-1, but for everyday use, not for
demonstrations. All of its programs are presented in this book as well and are included in the
examples distribution package. See the end of Chapter 10 for more on PyDemos and PyGadgets.
Setup requirements
Most demos and gadgets require a Python with Tkinter GUI support, but that is the default
configuration for Python out-of-the-box on Windows. As a result, most of the demos and gadgets
should "just work" on Windows. On some other platforms, you may need to install or enable Tkinter
for your Python; try it and seeif you get an error about Tkinter not being found, you'll need to
configure it. If it's not already present, Tkinter support can be had freely on the Web for all major
platforms (more on this in the GUI part of this book, but search the Web with Google for quick
pointers).
36.
Two external dependencynotes: PyPhoto will not run without PIL, and PyMailCGI runs without
PyCrypto but uses it if installed. Both PIL and PyCrypto are open source third-party extension
packages, but must be installed in addition to Python. Some book examples use additional third-
party tools (for instance, ZODB and MySQL in the database chapter), but these are not launched
from the demos and gadgets interfaces.
To run the files listed in the preceding section directly, you'll also need to set up your Python module
search path, typically with your PYTHONPATH environment variable or a .pth file. The book examples
tree ships as a simple directory and does not use Python's Distutils scripts to install itself in your
Python's site packages directory (this system works well for packed software, but can add extra steps
for viewing book examples).
If you want to run a collection of Python demos from the book right away, though, and you don't
want to bother with setting up your environment first, simply run these self-launching utility scripts in
the PP3E directory instead:
Launch_PyDemos.pyw
Launch_PyGadgets_bar.pyw
Launch_PyGadgets.py
These Python-coded launcher scripts assume Python has already been installed, but will automatically
find your Python executable and the book examples distribution and set up your Python module and
system search paths as needed to run their programs. You can probably run these launcher scripts
by simply clicking on their names in a file explorer, and you should be able to run them directly from
the book's examples package tree (you can read more about these scripts in Part II of the book).
Web-based examples
Beginning with this edition of the book, its browser-based Internet examples are not installed on a
remote server. Instead, we'll be using a Python-coded web server running locally to test these
examples. If you launch this server, though, you can also test-drive browser-based examples too.
You can find more on this in the Internet section of this book.
For a quick look, though, PyDemos attempts to launch both a web server and a web browser on your
machine automatically for the major example web pages. You start the browser by running the
LaunchBrowser.py script in the examples root directory. That script tries to find a usable browser on
your machine, with generally good results; see the script for more details if it fails. The server is
implemented by a Python script, assuming you have permission to run an HTTP server on your
machine (you generally do on Windows).
Provided the server starts and LaunchBrowser can find a browser on your machine, some demo
buttons will pop up web pages automatically. Figure P-2, for example, shows the web examples index
page running under a local server and the Firefox browser.
Figure P-2. The PyInternetDemos web page
37.
Clicking this page'slinks runs various server-side Python CGI scripts presented in the book. Of
special interest, the getfile.html link on this page allows you to view the source code of any other file
in the book's web server directoryHTML code, Python CGI scripts, and so on; see Chapter 16 for
details.
Top-level programs
To summarize, here is what you'll find in the top-level ExamplesPP3E directory of the book's
examples package:
PyDemos.pyw
Button bar for starting major GUI and Internet examples in demo mode
PyGadgets_bar.pyw
38.
Button bar forstarting GUIs in PyGadgets on demand
PyGadgets.py
Starts programs in nondemo mode for regular use
Launch_*.py*
Starts the PyDemos and PyGadgets programs using Launcher.py to autoconfigure search paths
(run these for a quick look)
LaunchBrowser.py
Opens example web pages with an automatically located web browser
Launcher.py
Utility used to start programs without environment settingsfinds Python, sets PYTHONPATH, and
spawns Python programs
You'll also find subdirectories for examples from each major topic area of the book. In addition, the
top-level PP3EPyTools directory contains Python-coded command-line utilities for converting line
feeds in all example text files to DOS or Unix format (useful if they look odd in your text editor);
making all example files writable (useful if you drag-and-drop off a CD on some platforms); deleting
old .pyc bytecode files in the tree; and more. Again, see the example directory's README-PP3E.txt
file for more details on all example issues.
Conventions Used in This Book
The following font conventions are used in this book:
Italic
Used for file and directory names, to emphasize new terms when first introduced, and for some
comments within code sections
Constant width
Used for code listings and to designate modules, methods, options, classes, functions,
statements, programs, objects, and HTML tags
Constant width bold
Used in code sections to show user input
Constant width italic
39.
Used to markreplaceables
This icon designates a note related to the nearby text.
This icon designates a warning related to the nearby text.
Safari® Enabled
When you see a Safari® Enabled icon on the cover of your favorite technology book,
that means the book is available online through the O'Reilly Network Safari Bookshelf.
Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search
thousands of top tech books, cut and paste code samples, download chapters, and find quick
answers when you need the most accurate, current information. Try it for free at
http://safari.oreilly.com.
Where to Look for Updates
As before, updates, corrections, and supplements for this book will be maintained at the author's web
site, http://www.rmi.net/~lutz. Look for the third edition's link on that page for all supplemental
information related to this version of the book. As for the first two editions, I will also be maintaining
a log on this web site of Python changes over time, which you should consider a supplemental
appendix to this text. O'Reilly's web site, http://www.oreilly.com, also has an errata report system,
and you should consider the union of these two lists to be the official word on book bugs and
updates.
Contacting O'Reilly
You can also address comments and questions about this book to the publisher:
O'Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States and Canada)
707-827-7000 (international/local)
707-829-0104 (fax)
O'Reilly has a web page for this book, which lists errata, examples, and any additional information.
You can access this page at:
40.
http://www.oreilly.com/catalog/python3
To comment orask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about books, conferences, software, Resource Centers, and the O'Reilly
Network, see the O'Reilly web site at:
http://www.oreilly.com
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in this book in
your programs and documentation. You do not need to contact us for permission unless you're
reproducing a significant portion of the code. For example, writing a program that uses several
chunks of code from this book does not require permission. Selling or distributing a CD-ROM of
examples from O'Reilly books does require permission. Answering a question by citing this book and
quoting example code does not require permission. Incorporating a significant amount of example
code from this book into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author,
publisher, and ISBN. For example: "Python Programming, Third Edition, by Mark Lutz. Copyright
2006 O'Reilly Media, Inc., 978-0-596-00925-0."
Acknowledgments
In closing, I would like to extend appreciation to a few of the people who helped in some way during
all the incarnations of this book project:
To this book's first editor, the late Frank Willison, for the early years.
To this book's later editors, for tolerating my nondeterministic schedule: Laura Lewin on the
second edition, Jonathan Gennick on the third edition, and Mary O'Brien at the end.
To the people who took part in a technical review of an early draft of this edition: Fredrik Lundh,
Valentino Volonghi, Anna Ravenscroft, and Kyle VanderBeek.
To Python creator Guido van Rossum, for making this stuff fun again.
To Tim O'Reilly and the staff of O'Reilly, both for producing this book and for supporting open
source software in general.
To the Python community at large, for quality, simplicity, diligence, and humor.
To C++, for frustrating me enough to compel me toward Python; I think I'd rather flip burgers
than go back :-).
To the thousands of students of the 170 Python classes I have taught so far, for your feedback
on Python in general, and its applications. You taught me how to teach.
To the scores of readers who took the time to send me comments about the first two editions of
41.
this book. Youropinions helped shape this book's evolution.
And finally, a few personal notes of thanks. To all the friends I've met on the training trail, for
hospitality. To my mom, for wisdom and courage. To OQO, for toys. To my brothers and sister, for
old days. To Guinness, for the beer in Dublin. To Birgit, for inspiration and spleenwurst. And to my
children, Michael, Samantha, and Roxanne, for hope.
Mark Lutz
April 2006
Somewhere in Colorado, or an airport near you
42.
Part I: TheBeginning
This part of the book gets things started by introducing the Python language and taking us on a
quick tour of some of the most common ways it is applied.
Chapter 1
Here, we'll take a "behind the scenes" look at Python and its world by presenting some of
its history, its major uses, and the common reasons people choose it for their projects.
This is essentially a management-level, nontechnical introduction to Python.
Chapter 2
This chapter uses a simple examplerecording information about peopleto briefly introduce
some of the major Python application domains we'll be studying in this book. We'll
migrate the same example through multiple steps. Along the way, we'll meet databases,
GUIs, web sites, and more. This is something of a demo chapter, designed to pique your
interest. We won't learn much here, but we'll have a chance to see Python in action before
digging into the details. This chapter also serves as a review of some core language ideas
you should be familiar with before starting this book, such as data representation and
object-oriented programming (OOP).
The point of this part of the book is not to give you an in-depth look at Python, but just to let
you sample its application. It will also provide you with a grounding in Python's broader goals
and purpose.
43.
Chapter 1. IntroducingPython
Section 1.1. "And Now for Something Completely Different"
Section 1.2. Python Philosophy 101
Section 1.3. The Life of Python
Section 1.4. Signs of the Python Times
Section 1.5. The Compulsory Features List
Section 1.6. What's Python Good For?
Section 1.7. What's Python Not Good For?
Section 1.8. Truth in Advertising
44.
1.1. "And Nowfor Something Completely Different"
This book is about using Python, an easy-to-use, flexible, object-oriented, mature, popular, and open
source[*] programming language designed to optimize development speed. Although it is completely
general purpose, Python is often called a scripting language, partly because of its sheer ease of use
and partly because it is commonly used to orchestrate or "glue" other software components in an
application. Python is also commonly known as a high-level language, because it automates most
low-level tasks that programmers must handle manually in traditional languages such as C.
[*] Open source systems are sometimes called freeware, in that their source code is freely distributed and community controlled.
Don't let that concept fool you, though; with roughly 1 million users in that community today, Python is very well supported. For more
information on open source, see http://opensource.org.
If you are new to Python, chances are you've heard about the language somewhere but are not quite
sure what it is about. To help you get started, this chapter provides a general introduction to
Python's features and roles. Most of it will make more sense once you have seen real Python
programs, but let's first take a quick pass over the forest before wandering among the trees. In this
chapter, we'll explore Python's philosophy, its history, and some of its most prominent benefits and
uses, before digging into the details.
45.
1.2. Python Philosophy101
In the Preface, I mentioned that Python emphasizes concepts such as quality, productivity,
portability, and integration. Since these four terms summarize most of the reasons for using Python,
I'd like to define them in a bit more detail.
Software quality
Python makes it easy to write software that can be understood, reused, and modified. It was
deliberately designed to raise development quality expectations in the scripting world. Python's
clear syntax and coherent design, for example, almost force programmers to write readable
codea critical feature for software that may be changed or reused by others in the future.
Of equal importance, because the Python language tries to do better, so too do Python
developers and the Python community at large. In the Python world, one finds a refreshing
focus on quality concepts such as simplicity, explicitness, and readabilityideas often given little
more than a passing glance in some camps. (For more on this Python-inspired mindset, see the
sidebar "The Python 'Secret Handshake'," near the end of this chapter.)
The Python language really does look like it was designed and not accumulated. It has an
orthogonal, explicit, and minimalist design that makes code easy to understand and easy to
predict. Python approaches complexity by providing a simple core language and splitting
application-specific tools into a large set of modular library components.
As a popular slogan attests, the result is that Python "fits your brain"it's possible to use the
language without constantly flipping through reference manuals. This design makes Python
ideal as a customization language for nonexperts. Perhaps most important is that by limiting
the number of possible interactions in your code, Python reduces both program complexity and
the potential for bugs.
Besides being well designed, Python is also well tooled for modern software methodologies
such as structured, modular, and object-oriented design, which allow code to be written once
and reused many times. In fact, due to the inherent power and flexibility of the language,
writing high-quality Python components that may be applied in multiple contexts is almost
automatic.
Developer productivity
Python is optimized for speed of development. It's easy to write programs fast in Python,
because the interpreter handles details you must code explicitly in more complex, lower-level
languages. Things such as type declarations, storage layout, memory management, common
task implementations, and build procedures are nowhere to be found in Python scripts.
In fact, programs written in Python are typically one-third to one-fifth as large as they would be
in a language like C++ or Java, and these ratios directly correlate to improved programmer
speed. Because of Python's high-level design, Python developers have less to code, less to
debug, and less to maintain.
46.
The result isa remarkably flexible and agile language, useful for both quick tactical tasks such
as testing and system administration, as well as larger and long-term strategic projects
employing design and analysis tools.
Today, developers use Python for everything from five-line scripts to systems composed of
more than 1 million lines of Python code (including IronPort's email security products suite). Its
tool set allows it to scale up as needed. In both modes, Python programmers gain a crucial
development speed advantage because of the language itself, as well as its library of precoded
tools.
For instance, the lack of type declarations alone accounts for much of the conciseness and
flexibility of Python code: because code is not restricted to a specific type, it is generally
applicable to many types. Any object with a compatible interface will do. And although Python
is dynamically typedtypes are tracked automatically instead of being declared (it is still strongly
typed)every operation is sanity checked as your program runs. Odd type combinations are
errors in Python, not invocations of arbitrary magic.
But fast initial development is only one component of productivity. In the real world,
programmers must write code both for a computer to execute and for other programmers to
read and maintain. Because Python's syntax resembles executable pseudocode, it yields
programs that are easy to understand, change, and use long after they have been written. In
addition, Python supports (but does not impose) advanced code reuse paradigms such as
object-oriented programming, which further boost developer productivity and shrink
development time.
Program portability
Most Python programs run without modification on nearly every computer system in use
todayon Windows, Linux, Macintosh, and everything from IBM mainframes and Cray
supercomputers to real-time systems and handheld PDAs. Python programs even run on more
exotic devices such as game consoles, cell phones, and the Apple iPod. Although some
platforms offer nonportable extensions, the core Python language and libraries are largely
platform neutral and provide tools for dealing with platform differences when they arise.
For example, most Python scripts developed on Windows, Linux, or Macintosh will generally run
on the other two platforms immediatelysimply copy the script's source code over to the other
platforms. Moreover, a GUI program written with Python's standard Tkinter library will run on
the X Windows system, Microsoft Windows, and the Macintosh, with native look-and-feel on
each and without modifying the program's source code. Alternative toolkits such as wxPython
and PyQt offer similar GUI portability.
Component integration
Python is not a closed box: it is also designed to be integrated with other tools. Programs
written in Python can be easily mixed with and can script (i.e., direct) other components of a
system. This makes Python ideal as a control language and as a customization tool. When
programs are augmented with a Python layer, their end users can configure and tailor them,
without shipping the system's entire source code.
More specifically, today Python scripts can call out to existing C and C++ libraries; use Java
classes; integrate with COM, .NET, and CORBA components; communicate with other
components over network protocols such as sockets, HTTP, XML-RPC, and SOAP; and more. In
addition, programs written in other languages can just as easily run Python scripts by calling C
and Java API functions, accessing Python-coded COM and network servers, and so on. Python
allows developers to open up their products to customization in a variety of ways.
47.
In an eraof increasingly short development schedules, faster machines, and heterogeneous
applications, these strengths have proven to be powerful allies to hundreds of thousands of
developers, in both small and large development projects.
Naturally, there are other aspects of Python that attract developers, such as its simple learning curve
for developers and users alike, vast libraries of precoded tools to minimize upfront development, and
a completely free nature that cuts product development and deployment costs.
Python's open source nature, for instance, means that it is controlled by its users, not by a financially
vested company. To put that more forcefully, because Python's implementation is freely available,
Python programmers can never be held hostage by a software vendor. Unlike commercial tools,
Python can never be arbitrarily discontinued. Access to source code liberates programmers and
provides a final form of documentation.
At the end of the day, though, Python's productivity focus is perhaps its most attractive and defining
quality. As I started writing the second edition of this book in the Internet bubble era of 1999, the
main problem facing the software development world was not just writing programs quickly, but
finding developers with the time to write programs at all. As I write this third edition in the post-
boom era of 2005, it is perhaps more common for programmers to be called on to accomplish the
same tasks as before, but with fewer resources. In both scenarios, developers' time is paramountin
fact, it's usually much more critical than raw execution speed, especially given the speed of today's
computers.
As a language optimized for developer productivity, Python seems to be the right answer to the
questions asked by the development world. It allows programmers to accomplish more in less time.
Not only can Python developers implement systems quickly, but the resulting systems will be
reusable, maintainable by others, portable across platforms, and easily integrated with other
application components.
Why Not Just Use C or C++?
I'm asked this question quite often, and if you're new to the scripting languages domain,
you might be puzzling over this question yourself. After all, C runs very fast and is widely
available. So how did Python become so popular?
The short storyone we'll see in action firsthand in this bookis that people use scripting
languages rather than compiled languages like C and C++ because scripting languages
are orders of magnitude easier and quicker to use. Python can be used in long-term
strategic roles too, but unlike compiled languages, it also works well in quick, tactical
mode. As an added benefit, the resulting systems you build are easier to change and
reuse over time.
This is especially true in the web domain, for example, where text processing is so
central, change is a constant, and development speed can make or break a project. In
domains like these:
Python's string objects and pattern matching make text processing a breezethere is
no need to limit the size of strings, and tasks like searching, splitting,
concatenation, and slicing are trivial. In C, such tasks can be tedious, because
everything is constrained by a type and a size.
Python's general support for data structures helps here tooyou just type a complex
48.
nested dictionary literal,for example, and Python builds it. There is no need to lay
out memory, allocate and free space, and so on.
The Python language itself is much simpler to code. Because you don't declare
types, for instance, your code not only becomes shorter, but also can be applied
and reused in a much wider range of contexts. When there is less to code,
programming is quicker. And the runtime error checking provided by scripting
languages like Python makes it easier to find and fix bugs.
Just as important is that a vast collection of free, web-related software is available
for Python programmers to useeverything from the client and server-side protocol
modules in the standard library, to third-party web application frameworks such as
Zope, Plone, CherryPy, Django, and Webware. These greatly simplify the task of
building enterprise-level web sites.
In other domains, the same factors apply but with different available tool sets. In fact,
after you use Python for awhile, you'll probably find that it enables things that you would
have never considered doing in a compiled language because they would have been too
difficult. Network scripting, GUIs, multitasking, and so on, can be cumbersome in C but
are easy in Python.
The bottom line is that C is just too complex, rigid, and slow, especially for web work. In
such a dynamic domain, you need the flexibility and rapid development of a scripting
language like Python. Compiled languages can run faster (depending on the sort of code
you run), but speed of development tends to overshadow speed of execution on the
Web. You should be warned, thoughonce you start using Python, you may never want to
go back.
49.
1.3. The Lifeof Python
Python was invented around 1990 by Guido van Rossum, when he was at CWI in Amsterdam. It is
named after the BBC comedy series Monty Python 's Flying Circus, of which Guido is a fan (see this
chapter's sidebar "What's in a Name?"). Guido was also involved with the Amoeba distributed
operating system and the ABC language. In fact, his original motivation for creating Python was to
create an advanced scripting language for the Amoeba system. Moreover, Python borrowed many of
the usability-study-inspired ideas in ABC, but added practicality in the form of libraries, datatypes,
external interfaces, and more.
The net effect was that Python's design turned out to be general enough to address a wide variety of
domains. It is now used in increasingly diverse roles by hundreds of thousands of engineers around
the world. Companies use Python today in commercial products for tasks as diverse as web site
construction, hardware testing, numeric analysis, customizing C++ and Java class libraries, movie
animation, and much more (more on roles in the next section). In fact, because Python is a
completely general-purpose language, its target domains are limited only by the scope of computers
in general.
Since it first appeared on the public domain scene in 1991, Python has continued to attract a loyal
following and has spawned a dedicated Internet newsgroup, comp.lang.python, in 1994. As the first
edition of this book was being written in 1995, Python's home page debuted on the Web at
http://www.python.orgstill the official place to find all things Python. A supplemental site, the Vaults
of Parnassus, serves as a library of third-party extensions for Python application development (see
http://www.vex.net/parnassus). More recently, the Python Package Index site (PyPI at
http://www.python.org/pypialso known as the "Python Cheese Shop"began providing a
comprehensive and automated catalog of third-party Python packages.
To help manage Python's growth, organizations that are aimed at supporting Python developers have
taken shape over the years: among them, the now defunct Python Software Activity (PSA) was
formed to help facilitate Python conferences and web sites, and the Python Consortium was formed
by organizations interested in helping to foster Python's growth. More recently, the Python Software
Foundation (PSF) was formed to own the intellectual property of Python and coordinate community
activities, and the Python Business Forum (PBF) nonprofit group addresses the needs of companies
whose businesses are based on Python. Additional resources are available for Python training,
consulting, and other services.
Today, Guido is employed by Google, the web search-engine maker and a major Python user, and he
devotes a portion of his time to Python. A handful of key Python developers are also employed by
Zope Corporation, home to the Python-based Zope web application toolkit (see http://www.zope.org
and Chapter 18; Zope is also the basis of the Plone web content management system). However, the
Python language is owned and managed by an independent body, and it remains a true open source,
community-driven, and self-organizing system. Hundreds, if not thousands, of individuals contribute
to Python's development, following a now formal Python Enhancement Proposal (PEP) procedure and
coordinating their efforts online.
Other companies have Python efforts underway as well. For instance, ActiveState and PythonWare
develop Python tools, O'Reilly (the publisher of this book) and the Python community organize annual
Python conferences (OSCON, PyCon, and EuroPython), and O'Reilly manages a supplemental Python
web site (see the O'Reilly Network's Python DevCenter at http://www.oreillynet.com/python).
Although the world of professional organizations and companies changes more frequently than do
QUESTIONS OF FOREIGNPOLICY BEFORE THE
CABINET
Speech delivered before the Cabinet on 7th April 1923.
The Abbazia Conference. Colleagues,—The Commission appointed
according to the Agreements of Santa Margherita, which met, as is
known, on 1st March, started its work by the arrangement for the
evacuation of Susak, which took place on the following day. It is
opportune here to note that the Italian Delegation wished to express
to the world and to the Italian troops its gratitude for the courteous
and chivalrous behaviour during the whole occupation of Susak.
The Commission decided, at that time, a provisional settlement for
communication and traffic between Fiume and Susak, which was
made effective for two months, in view of the eventuality of the
prorogation of the sittings of the Commission. The frontier traffic
between Castua and the adjacent territories was also organised.
With reference to the military operations, the Serbo-Croatian-
Slovak Delegation has at once recorded an objection, on the grounds
that with the evacuation of Susak, it did not consider that that
stipulated by the Agreements of Santa Margherita had been carried
out, seeing that the Delta and Porto Sauro remained occupied by
Italian troops. Against this assertion the Italian Delegation replied
that Italy had carried out to the letter the provisions of the
Agreements of Santa Margherita, which refer purely and simply to
the evacuation of Susak.
Apart from this objection, the Commission has continued its work
and the Italian Delegation has put forward a project for a
Consortium in the port of Fiume between the three interested
States. Such a project, in a general way, attributes to Fiume the
53.
character of aninternational port, leaving the possibility of the
enjoyment of special privileges and guarantees to each of the
contracting States for a freer development of the traffic which affects
them. With regard to such a project, the Serbo-Croatian-Slovak
Delegation has put forward its objections, presenting on its own
account a draft of a project, according to which the Sauro Basin and
the Delta would be excluded from the port of Fiume and assigned
exclusively to Yugoslavia.
The Italian Delegation has formally declared that it could not
accede to any pact whatsoever which, destroying the unity of the
port of Fiume, would irremediably damage the future of the new
State, and, in answer to the objections raised by the Serbo-Croatian-
Slovak Delegation to the Italian project, our Delegation has
presented another plan, in which full consideration was given to the
said exceptions. But, in the course of the following discussion, the
points of view of the two Delegations could not be reconciled. The
sittings were suspended on 24th March, to be resumed shortly.
The new Lausanne Conference. Following the counterproposals
put forward by the Government of Angora, the British Government
has convened in London an Inter-Allied meeting in order to examine
what modifications to the drafting and the substance of the Peace
Treaty presented to the Turks on the 30th of last January may be
possible. The Allied Representatives at this meeting have decided to
invite the Turks to resume as soon as possible at Lausanne the
discussion with the Allied experts and have at the same time come
to an agreement as to the line of conduct to follow in such a
discussion.
In the text of the reply sent to the Government of Angora, which
has been published, the Allies have deemed it opportune to insert
some remarks and objections on certain points of special
importance, as for example that regarding the removal of the
Economic Clauses asked by the Turks, to which the Allies cannot
accede; that concerning some part of the judiciary declarations and
54.
the Turkish demandsrelative to substantial modifications of the
Territorial Clauses already agreed upon, such as that of Castelrosso,
whose restoration to Turkey could not be countenanced.
It is to be hoped that the good-will that both parties have the
intention of displaying in the imminent negotiations of Lausanne may
bring about speedily the conclusion of peace in the East, which
corresponds with the warmest wish and interest of the Italian
Government.
Italo-Polish Relations. Mr. Skrzynski came to Milan to express to
me the gratitude of Poland for the friendly attitude of Italy in the
determination of the Polish frontier, which took place recently.
Expressing a personal view, I mentioned to him the advisability of a
larger extension of autonomy to the population of Eastern Galicia. I
profited by the occasion to examine with the Minister for Foreign
Affairs some concrete points, which, with regard to oil and coal,
concern more closely our commerce. I recognised with satisfaction
the friendly disposition which animates the Polish Government and I
was struck with the impression that whenever important Italian
enterprises should wish to develop their activity in Poland, they
would find there the best of welcomes. The representatives of some
Italian firms of standing, moreover, are now already in negotiation at
Warsaw, and the results, I hope, will in a short time confirm the
favourable attitude of the Polish Foreign Minister.
The Visit of the Austrian Chancellor Seipel. In the conversations I
had at Milan with the Austrian Chancellor, both parties expressed the
reciprocal desire and interest to improve further relations between
the two countries. The Chancellor has warmly thanked the Italian
Government for the helpful action on behalf of Austria and has asked
our support for the satisfactory solution of all problems which might
contribute to the economic reconstruction of the Republic. I gave
favourable assurances and, consequently, have accordingly hastened
the negotiations already begun for a commercial agreement and I
55.
have had examinednumerous questions which had been dragging
on unsolved for some time.
It is to be hoped that, the last difficulties having been removed,
the Commercial Treaty may be signed within a few days. The
Clauses of the Portorose Conventions, signed and not ratified by the
contracting parties, will be included in it. The Chancellor has asked
that the small Austrian properties in Italy and the historical Austrian
Institute in Rome should be restored to Austria, as was done for
Germany. While I declared myself favourable to his requests, I have,
for my part, reminded him of the situation of Italian property in
Austria and have obtained from the Chancellor satisfactory
assurances concerning this and other subjects. With reference to the
Conventions signed at the Conference of Rome, some of which have
notable importance for Italy, the Chancellor has promised to proceed
to their ratification without further delay.
The Commercial Relations with Austria. The negotiations with
Austria are being conducted with a spirit of the greatest good-will on
both sides, in order to arrive in a short space of time at an
agreement which should establish regular and profitable relations
between the two countries and also after the first period, during
which the economic relations between the two States are regulated
by the Treaty of St. Germain. If some difficulty still remains, this is
due in the first place to the fact that it is not the case of negotiating
pacts which, with regard to their application and their consequences,
could remain restricted to the exchanges between the two
neighbouring States, but are destined to have a repercussion also on
our relations with the other States which, for their imports into Italy,
enjoy the “most favoured nation” clause.
This fact, independently of the specially favourable conditions by
which certain important industries, competing with ours, are working
in Austria, compels us to be very cautious in adhering to the many
Austrian requests, and all the more that, for financial and other
reasons, Austria is herself not in a position to meet our demands to
56.
the extent whichis essential to us. The two Delegations have,
however, already arrived at an agreement on most of the questions
which have been the subject of reciprocal demands, and now certain
controversies remain to be solved which, although they offer the
greatest interests for both sides, it is to be hoped may be solved
with satisfaction to all.
Special attention has been paid by the two Delegations to the
study of the questions relative to the traffic through the port of
Trieste and the regulation of the frontier traffic for the protection of
the interests of the populations of the zone near the frontier of the
two States. On this subject agreement may be said to be complete.
The Commercial Treaty with Yugoslavia. The negotiations with
Yugoslavia, which should lead to the regulation of all the economic
and financial questions still pending between the two States, have
been conducted so far on the Treaty of Commerce, which, except for
the part concerning the Italian proposals on the tariffs, may be said
to be already agreed upon by the two Delegations. With reference to
the other subjects under examination, of which only a small part has
been possible to discuss at the same time as the negotiations for the
Commercial Treaty, the Yugoslav Delegation is now awaiting further
instructions from Belgrade. Besides the commercial negotiations I
have mentioned, there are others proceeding for a Commercial
Treaty with Spain. Negotiations will shortly be opened for
commercial agreements with Siam, Finland, Esthonia, Lithuania,
Lettonia and Albania.
(After a short discussion, in which several Ministers participated,
the Cabinet approved the declarations of the Prime Minister.)
57.
“MINE IS NOTA GOVERNMENT WHICH
DECEIVES THE PEOPLE”
Speech delivered at the Palazzo Municipale on 2nd June 1923, to the contadini of
Rovigo.
Fascisti,—How shall I find adequate words to thank you for this
magnificent welcome? A few moments ago your mayor gave voice to
the greeting of the city and the province. To-day I have passed
through your fertile lands, furrowed by rivers, exploited by your
tenacious work. All Italy must be grateful to this industrious people,
who, too, having realised the beautiful and supreme interests of the
nation, has now all the more the right to be treated with greater
friendship and consideration.
I know that I am speaking to an assembly where workers are
certainly in enormous majority. Well, I say to them with calm words
and with a still calmer conscience that the Government which I have
the honour to represent is not, cannot, and will never be against the
working classes. (Loud applause.) Six months of Government are still
too few for a programme to be carried through, but, to my mind,
they are sufficient to give an idea of its directives which to-day are
precise and sound. Mine is not a Government which deceives the
people. (Applause.) We cannot, we shall not, make promises if we
are not mathematically sure of being able to fulfil them. The people
have been too long deceived and mystified for the men of our
generation to continue this low trade.
We have traced a furrow, very clear-cut and deep, between that
which was the Italy of yesterday and that which is the Italy of to-
day. In the latter, all classes must have a sphere of action for their
fruitful co-operation. The struggle between classes may be an
58.
episode in thelife of a people, it cannot be the daily system, as it
would mean the destruction of wealth, and, therefore, universal
poverty. The co-operation, citizens, between him who labours and
him who employs labour, between him who works with his hands
and him who works with his brains, all these elements of production
have their inevitable and necessary grades and constitutions.
Through this programme you will attain a state of well-being and the
nation prosperity and greatness. If I were not sure of my words I
would not utter them before you on such a solemn and memorable
occasion. (Applause.)
(At this point of the speech an aeroplane piloted by Ferrarin was
executing some daring evolutions just above the Palazzo Municipale,
from where Mussolini was speaking. The Prime Minister stopped for
a few seconds following Ferrarin’s evolutions, then went on:)
Fascisti! The other day I was passing in one of those aeroplanes
over your town. That flight was profoundly significant, as it was
meant to show that six months of tenure of office have not yet
nailed me down into my Presidential easy chair and that I, as you, as
all of you, am still ready to dare, to fight, if necessary, to die, so that
the fruits of the great Fascista revolution may not be lost!
Long live Fascismo! Long live Italy! (Loud applause.)
60.
“IN TIME PASTAS IN TIME PRESENT, WOMAN
HAD ALWAYS A PREPONDERANT INFLUENCE
IN SHAPING THE DESTINIES OF HUMANITY”
Speech delivered at Padua at the first Women’s Fascista Congress, on 2nd June
1923.
Ladies,—If I am not mistaken, this, which is inaugurated here to-
day, is the first Women’s Fascista Congress of the “three Venices.”
The title and the field covered by this first Congress of yours are full
of profound significance. Fifty years ago one could not speak of the
“three Venices”! Venice herself, after the magnificent years of
heroism of 1848 and 1849, was still held by the shackles of foreign
slavery. In 1866 we liberated Venice, one of the Venices. Fifty years
afterwards we liberated the other two—that which has as its
boundary the devoted and impregnable Brenner, and the other
which has as its boundary the not less devoted nor less impregnable
Nevoso.
Fascisti do not belong to the multitude of fops and sceptics who
mean to belittle the social and political importance of woman. What
does the vote matter? You will have it! But even when women did
not vote and did not wish to vote, in time past as in time present,
woman had always a preponderant influence in shaping the destinies
of humanity. Thus the women of Fascismo, who bravely wear the
glorious “black shirt,” and gather round our standards, are destined
to write a splendid page of history, to help, with self-sacrifice and
deeds, Italian Fascismo.
Do not trust the little stuffed owls, the yelling monkeys or, indeed,
any representative of the lower zoological orders, who believe they
practise politics, but could be called by a more infamous name. Do
61.
not believe thosewho talk of crises within the ranks of Fascismo;—
these are details, mere episodes in the great event, and they, after
all, concern men, not masses. When Fascisti have not to strike the
enemy, they can well afford themselves the luxury of internal
quarrels. But if the enemy should begin to raise his head again and
intensify the character of his more or less stupid opposition, then
Fascisti will again become solidly united. Then “Woe to the
vanquished!” (Applause.) And since the opportunity is propitious, I
would like to tell you, women of Fascismo, and the Fascisti of all
Italy, that the attempt to sever Mussolini from Fascismo or Fascismo
from Mussolini is the most useless and grotesque attempt that could
be conceived. (Applause.) I am not so proud as to say that I who
speak and Fascismo are one; but four years of history have now
clearly shown that Mussolini and Fascismo are two aspects of the
same thing, are two bodies and one soul or two souls in a single
body. I cannot forsake Fascismo, because I have created it, I have
reared it, I have strengthened and I have chastened it, and I still
hold it in my fist, always! It is, therefore, quite useless for the old
screech-owls of Italian policy to pay me their foolish court. I am too
shrewd to fall into this ambush of the commercial mediocrities of
village fairs. I can assure you, my dear friends, that all these little
vipers, all these cheap politicians will be bitterly disillusioned.
To think that I could become brutalised in Parliamentary
bureaucracy is to believe an absurdity. Although I come from the
working class, I have a spirit too aristocratic not to feel disgust for
low Parliamentary manœuvres. We shall continue our march
vigorously (added the Hon. Mussolini, raising his voice), because this
has been imposed on us by destiny. We shall not turn back, nor shall
we even mark time. I have already said that we did not want to
push matters to extremes only to see ourselves driven back by the
swing of the pendulum. I prefer, as I wrote in an article, which
aroused some interest—I prefer to march on continually, day by day,
in the Roman way, in the way of Rome who is never reconciled to
defeat; of Rome who welcomed Terentius Varro coming from
Cannæ, although she knew that he had given battle against the
62.
opinion of ConsulPaulus Æmilius and was, in a certain degree,
responsible for the defeat; of Rome who after Cannæ forbade
matrons to sally forth, so that their grief-stricken bearing should not
shake the strength of the citizens; of this Rome who re-wrote
continually the chapters of her history, who found in every ill-success
the incentives to endurance, to steadfastness, to strengthen her
spirits, to harden her nerves, to light the flame of passion! This is
the Rome of whom we dream; the Rome in whom all hierarchies are
respected, those of strength, beauty, intelligence, and human
kindness; the Rome who struck hard at her enemies, but then raised
them up again and made them share her great destiny; the Rome
who left the utmost liberty to the beliefs of her subject-peoples,
provided only that they obeyed her!
Giuseppe Mazzini used to say that power is but the unity and
perseverance of all efforts put together. Well, Italian power, Fascista
power, the power of all the new generations which expand in this
superb spring of our life and history, will be the result of the unity of
our efforts, of the tenacity of our work. After all, what do Fascisti ask
for? They are not ambitious or factious. They have the sense of
limitation and of their responsibility. And I am sure of interpreting
your thought, the deep craving of your soul, if I say that Fascisti,
from the first to the last, from the leaders to the led, ask only one
thing: To serve with humility, with devotion, with steadfastness, our
beloved Mother Country, Italy! (The speech was greeted with
enthusiastic applause.)
63.
“SO LONG ASTHESE STUDENTS AND THESE
UNIVERSITIES EXIST, THE NATION CANNOT
PERISH AND BECOME A SLAVE, BECAUSE
UNIVERSITIES SMASH FETTERS WITHOUT
ALLOWING THE FORGING OF NEW ONES”
Speech delivered at the University of Padua on 3rd June 1923.
Mr. Chancellor, Professors, My Young Friends,—It is not I who
honour your University, it is your University which honours me, and I
must confess that, although on account of my laborious dealings
with men I am a little refractory to emotions, to-day, being among
you, I feel deeply touched.
We have known each other for some time, from 1915, from the
days of that May always radiant. I remember that the students of
Padua hung up at the doors of this University a big paper puppet
representing a politician about whom I do not wish to express any
opinion now. But that act meant that the youth of the University of
Padua did not want to hear about ignoble diplomatic bargains—
(Applause.)—did not want to sell its splendid spiritual birthright for a
more or less wretched mess of pottage. The University of Padua, the
students, who were not degenerate descendants of those Tuscan
students who went out to die at Curtatone and Montanara, wished
then to be the vanguard, to take up their post in the fighting line,
carrying with them the reluctant ones, chastening the pusillanimous,
overthrowing the Government and going out to fight, to sacrifice and
death, but also to honour and glory.
From that time I know that among you there are faithful followers
and that this University among all the others is truly an active centre
64.
of faith andof intense patriotism. If I look back for a moment to the
rolling by of centuries, I recognise in this University a great fountain
at which thousands of men of all countries, of all generations, of all
races, have quenched their thirst.
The Government which I have the honour to represent repudiates,
at any rate in the person of its chief, the doctrine of materialism and
the doctrines which claim to explain the very complex history of
humanity only from the material point of view, to explain an episode,
not the whole of history, an incident, not a doctrine. Well, this
Government prizes individual, spiritual and voluntary qualities, holds
in high esteem the Universities, because they represent so many
glorious strong points in the life of the people. In fact I do not
hesitate to state that if Germany has been able to resist the powerful
influence of Bolshevism, it is due, above all, to the strong University
traditions of that people.
A people with an ardent spirit and with genius like ours is
necessarily a well-balanced and harmonious one. The Government
understands the enormous historic importance of Universities, has a
respect for their noble traditions and wishes to raise them to the
heights of modern exigencies. All this cannot be done at once, as
everything cannot be accomplished in six months. All that we are
doing at present is to clear the ground from all the débris which the
rotten political caste has left us as a said inheritance. (Applause.)
How could a Government composed of former soldiers ever
disparage Universities? It would not only be absurd but criminal!
From the Universities have come out by the thousands volunteers
and by tens of thousands those magnificent warriors who used to
assault the enemy’s trenches with a superb contempt of death. They
are our comrades whose memory we bear engraved in our hearts.
You will write their names on your gates of bronze, but their memory
will be more imperishably engraved in our spirit. We cannot forget
them, as we cannot forget that out of the Universities came by
thousands the “black shirts,” those “black shirts” who, at a given
moment, put an end to the inglorious vicissitudes of Italian politics,
who took by the throat with strong fingers all the old profiteers who
65.
appeared, to theexuberant impatience of the new Italian
generations, always the more inadequate for their paralysing
decrepitude. (Applause.) Well, so long as there are Universities in
Italy—and there certainly will be for a long time—and so long as
there are young men to attend these Universities and to become
acquainted with the history of yesterday, thus preparing the history
of to-morrow, so long as there are such young men, the doors of the
past are definitely shut. I guarantee it formally! But I add further
that so long as these young men and these Universities exist, the
Nation cannot perish and it cannot become a slave, because
Universities smash fetters without forging new ones. (Applause.) If
to-morrow it were again necessary, either for causes arising within
or without the frontiers, to sound again the trumpet of war, I am
sure that the Universities would again empty themselves to re-
populate the trenches. (Loud applause.)
And now that you have rejuvenated me by twenty years, I would
like to sing with you the “Gaudeamus Igitur.” After all, Lorenzino dei
Medici was right when he sang: “How beautiful is youth!” Well, my
young friends, there can never be for us as individuals the certainty
of the morrow, but there is the supreme and magnificent certainty of
the morrow for us as a nation and as a people.
And with the students’ hymn, let us utter in Latin a simpler word,
Laboremus. To work with dignity, with probity and with cheerfulness,
to assault life with earnestness and to meet it as a mission, trying to
fulfil the categorical injunction left us by our dead. They command
us to obey and to serve, they command us discipline, sacrifice and
obedience.
We should really be the last of men if we failed to do our clear
duty. But we shall not fail. I who hold the pulse of the nation and
who carefully count its beats, I who sometimes shudder in the face
of the heavy responsibilities which I have assumed, feel in me a
hope, nay a vibration, of a supreme certainty which is this: that, by
the will of the leaders, by the determination of the people, and by
the sacrifice of past, present and future generations, Imperial Italy,
66.
the Italy ofour dreams, will be for us the reality of to-morrow. (Loud
applause.)
67.
ITALY’S FOREIGN POLICYREGARDING
GERMAN REPARATIONS, HUNGARY,
BULGARIA, AUSTRIA, YUGOSLAVIA, TURKEY,
RUSSIA, POLAND AND OTHER COUNTRIES
Speech delivered at the Senate on 8th June 1923.
Honourable Senators,—The speech that I have the honour of
delivering before your illustrious Assembly may appear analytical,
because in it I propose to touch on several questions and to speak
decisively upon several problems, especially with regard to internal
policy.[13]
By this I do not delude myself to be able to convince those
who are my opponents in malâ fide, nor to disperse completely the
small opposition which nourishes itself on detail, and is the effect of
personal temperament.
13. The speech on Internal Policy here referred to will follow this one on page
306.
You will not be surprised if I begin with foreign policy, even if it
happens that this is the field in which serious and founded
opposition does not exist, and it may be legitimately said that our
policy is endorsed unanimously by the nation.
As I have already said on other occasions, the foreign policy of the
present Government is inspired by the necessity for a progressive
revaluation of our diplomatic and political position in Europe and in
the world. It is a fact that, except for territorial acquisitions bounded
by the Brenner and the Nevoso, frontiers wrested by long and
bloody wars, Italy was excluded in the Peace of Versailles and other
successive treaties from all other benefits of an economic and
colonial nature. Solemn pacts signed during the war have lapsed and
68.
have not beenreplaced. The position of inferiority assigned to Italy
has weighed and still weighs heavily on the economic life of our
people. It is useless to dwell upon recriminations of the past. We
must rather seek to regain the ground and time lost. There is no
doubt that from October to to-day the situation has notably
improved.
The other Powers, whether allied or not, know that Italy intends
to follow an energetic and assiduous policy for the protection of her
natural and vital interests, intends to be present wherever, directly or
indirectly, they are at stake, because this is her right and her definite
duty; but at the same time she is in favour of that line of conduct in
general policy which tends to bring back as quickly as possible to a
normal state the economic situation of our continent. Italy, who too
is marching rapidly towards her readjustment, sees this re-birth
continually disturbed by general outside factors. There is, therefore,
a definite Italian interest in hastening the pacific solution of the
European crisis.
The Position of Italy and Reparations. All such crises, since the
Treaty of Versailles onwards, have been dominated by the one
problem: Reparations. In the face of this problem the fundamental
position of Italy is as follows:
1. Germany can and must pay a sum which now seems universally
fixed and which is very far from the many hundreds of milliards
talked of on the morrow of the Armistice;
2. Italy could not tolerate territorial changes which would lead to a
political, economic or military hegemony in Europe;
3. Italy is prepared to bear her quota of sacrifice, if it is necessary
to obtain what is called European reconstruction;
4. The Italian Government maintains to-day more than ever, above
all after the last German Note, that the problem of reparations and
that of Inter-Allied debts are intimately connected and are in a
certain sense interdependent.
69.
There is nodoubt that the occupation of the Ruhr has contributed
to render the crisis of the Ruhr extremely acute, and therefore to a
certain extent hastened a solution.
It will not be inopportune to recall, considering the rapidity of
events, that the French and Belgians went to the Ruhr on account of
the declarations of a series of failures of the supplies in kind by
Germany, admitted also by England, at any rate as regards that of
wood, and the failure of the Conference of Paris.
It is certainly worth while to fix exactly in their essential lines the
main features of the Italian, English and German projects, in order
to have a picture of the situation as regards its agreements and
divergencies, and to see what conjectures we can form as to a
possible settlement. This will also serve to explain why Italy was not
able to accept the Bonar Law scheme at Paris, and why she had to
reject the recent Cuno-Rosenberg Memorandum.
The Italian project reduced the German debt to fifty milliards of
gold marks, proposed a moratorium of two years, during which
Germany would continue the supply of reparations in kind, accepted
the distribution of German payments according to the quotas fixed
at Spa, by which the Italian quota was put at five milliards of gold
marks, fixed the payment of one part of the “C” bonds by means of
the security given by the other ex-enemy States, used the remainder
of the “C” bonds to settle the debt to America, agreed to the taking
of economic pledges as a guarantee of the German payments, and
finally, as regards the payments of the reparations owed by Austria,
Bulgaria and Hungary, asked for a pledge for the acceptance of the
proposals which England had deferred putting forward—proposals,
that is, of annulling those debts.
The Italian quota of reparations, which the Italian project fixed at
five milliards of gold marks, was thus reduced in the English project
to less than half; whilst cancelling the bonds, it partly abolishes to
our detriment German solidary responsibility for minor ex-enemy
debts and rendered impossible the execution of the agreement of
March 1921, which ensures important advantages to Italy upon the
basis of the “C” bonds. The larger percentage reserved on the
70.
seventeen milliards, representingthe interest of the moratorium
capitalised to 1923, could not be used for the payment of American
debts, in consideration of the aleatory nature of these seventeen
milliards.
I do not recall all this to reopen discussions, but only to make
clear the main outlines of that which was and remains a noteworthy
attempt to find a solution for this grave problem; an attempt which
contains worthy elements which can be usefully taken up again in
case of a definite settlement.
The conclusion of an agreement between England and America on
the problem of debts—the work of the then Chancellor of the
Exchequer, Mr. Baldwin, to-day Prime Minister, followed shortly after
the presentation of the English project.
Any idea of this debt being itself cancelled, or even of a simple
compensation through the payment of reparations, is excluded from
this agreement. The obligation to pay, although facilities may be
accorded concerning both the number of years in which it must take
place and the interests due, is solemnly affirmed and put into
execution. In England the Speech from the Throne strongly
emphasised this agreement. Even taking into account the diversity of
economic strength and the totality of sacrifices borne, it could not
remain without effect upon the importance of the whole question for
the other European Powers.
Analysis of the German Project. If we compare the English and
Italian projects with the German, the inacceptability of the latter
appears evident. As is known, one of the fundamental points of the
last German project concerns the consolidation of the actual debt of
Germany, especially in kind, at the figure of twenty milliard gold
marks, with an additional ten milliards, the payment of which
depends upon the decision of an International Commission.
Deducting the interest, these twenty milliards are reduced to fifteen,
and the sums necessary must be found by international loans; and
in the very probable eventuality that by 1927 the twenty milliards
71.
have not beensubscribed, an annuity will be paid which represents
five per cent. interest plus one per cent. for the redemption of the
loan. Finally, in the German project any provision or regulation for
the guarantees demanded is lacking. The total German debt, which
in the English and the Italian projects is fixed at the figure of fifty
milliards, in the German project is reduced to less than a third, and it
is difficult, if not impossible, to determine in it the Italian quota and
the sacrifice demanded from Italy.
In view of the representations, especially of England and Italy,
Germany has recognised her proposals as insufficient, and yesterday
the German Ambassador, Neurath, presented to me the new German
Note, on the contents and nature of which I cannot pronounce an
opinion for evident reasons, as in consequence of this Note
diplomatic action with all the Allies must be taken up. I will only say
that the German Note no longer demands the preliminary evacuation
of the Ruhr as a condition for negotiation. This might make us
believe in a renunciation on the part of Germany of that passive
resistance, the utility of which—even for German aims—appears ever
more doubtful, and whose cessation would help towards a more
rapid attainment of a solution.
Italy and Hungary. But the problem of reparations is not only
Franco-German, it is also Hungarian, Bulgarian and Austrian.
It is useful to define the stage which has been reached with
regard to these ex-enemy countries. The total of the Hungarian
reparations, which is fixed by the Treaty of Trianon, has not yet been
determined by the Reparations Commission, and Hungary up to to-
day has only furnished limited supplies in kind. The Hungarian
Government, alleging the disturbed economic and financial
conditions of the country caused by the serious depression of the
krone, has recently put forward the necessity to contract a foreign
loan, which, if it is to succeed, should be guaranteed by the custom
duties, by the tobacco monopoly, and, if needs be, by other
resources. Hence arises the necessity for such resources to be freed
72.
for an adequateperiod from the claims of reparations. A
Memorandum precisely to this effect has been recently presented by
the Hungarian Minister in Paris to the Reparations Commission.
The Italian Government, having examined the question from a
technical point of view, has deemed it indispensable to concede to
Hungary the temporary relinquishment of certain resources, so that
she may proceed to her own economic restoration by means of loans
to be contracted abroad. Italy has, therefore, shown herself
favourable to the above Hungarian request, with the addition of
certain conditions necessary to guarantee her own rights, on which
point she is in agreement with the British Government.
Agreement with Bulgaria for Payment. With reference to Bulgarian
reparations, Italy, Great Britain and France came to an agreement on
21st March with the Bulgarian Government to facilitate the payment
of her debt of 2250 million gold francs fixed by the Treaty of Neuilly,
by dividing it in two parts; one of 550 millions to be paid by
instalments beginning in October of this year, and the other 1700
millions not to be claimed before thirty years.
Bulgaria has pledged herself by this agreement to reserve for the
regulation of her debt the revenues of her customs and has already
passed a law to this effect. The agreement has also been approved
by the Reparations Commission, with the reservation of our rights for
the reimbursement of the expenses of the army of occupation. In
fact, negotiations are proceeding with the Bulgarian Government for
the regulation of this credit, which enjoys the privilege of priority
over other reparations.
Our Government, animated by favourable dispositions as regards
all that concerns the settlement of obligations arising from the war,
has had no difficulty in accepting such an agreement.
The Loan to Austria. Fulfilling the pledge taken by its predecessors
in the Protocol of Geneva of 4th October 1922, the Italian
Government has co-operated with the Governments which are
73.
signatories of theProtocol, in order that the loan in favour of Austria
should have a large and ready success. For this purpose the
Government has consented to postpone for twenty years, which is
the duration of the War Loan, her credits against Austria for the
recovery of damages and for bonds of food supply, has given her
own guarantee for twenty-five per cent. of a maximum loan of 585
million gold kronen, and has authorised Italian banks to contribute
directly to the loan up to the maximum of 200 million lire, including
the sixty-eight which Italy had previously lent to Austria, and which,
by the terms of the Protocol of Geneva, should have been repaid in
cash.
Putting off for a further period the exaction of Austrian reparation,
and giving a guarantee and a direct and substantial contribution to
the loan in favour of Austria, the Italian Government has wished to
offer her co-operation towards the political independence and
territorial integrity of the Austrian Republic to which the Protocol of
Geneva refers, and to which the United States of America also wish
to contribute, confidently subscribing for the first time to a European
loan.
Relations between Italy and Yugoslavia. Italy’s political line of
conduct towards the States of the Little Entente and in general
towards the States recently created is substantially inspired by the
necessity of exacting the respect and the scrupulous fulfilment of the
treaties, because, given the present contingencies, only such a
policy can produce quick and pleasing results with regard to an
economic settlement of the Danubian States which would contribute
to the larger one of Central Europe. On several occasions the friendly
and moderate policy of Italy has followed such a course with
satisfactory results.
With reference to such a policy the relations between Italy and
Yugoslavia have a special importance. The clear attitude taken by
the Government with regard to Yugoslavia by proceeding to the
definite enforcement of the Treaty of Rapallo has strengthened our
74.
legal position, andwe are able to rest any further development of
our policy on a solid basis. The enforcement of the Agreements of
Santa Margherita, which has been necessarily laborious owing to the
large extent of the field covered, can be said, however, to proceed
on the whole satisfactorily. In spite of the initial difficulties
encountered in any exceptional régime, the economic system of the
so-called “special zone of Zara” is already in force for the evacuation
of the remaining Dalmatian territories, and the various organisations
for the regulation of all the intricate questions arising out of the
Agreements have been constituted.
Fiume. But naturally the most important question to solve is that
of Fiume. As is known, it offers the gravest difficulties, since, in
order to ensure the future of the commercial life of the town, there
must be solved many complex problems of an economic nature
which are often in opposition to those of a political character.
Undoubtedly the recent long Parliamentary crisis in Yugoslavia,
which for a considerable time forced the Government of Belgrade to
confine its attentions almost exclusively to internal problems, has
heavily weighed against the rapidity of the solution of such a
question.
That Government has repeatedly acquainted us with its wishes to
solve the question in a satisfactory way as regards the sentiments
and the interests of Italy, and has also frankly made known to us the
real difficulties with which the Government is faced in asking the
populations interested to accept a solution in agreement with the
Italian point of view.
Italo-Yugoslav Commission. With a view to ensure an atmosphere
of greater quiet to the Italo-Yugoslav Commission, the Government
of Belgrade has, in the meantime, agreed to transfer the seat of the
Commission to Rome. The Yugoslav Delegation has arrived, and
between it and the Italian Delegation, which is fulfilling its duty with
a high sense of patriotism and political probity, preliminary meetings
75.
are taking placewith the object of fixing certain fundamental points
before resuming official discussions, so that the latter may proceed
with the necessary speed without lapsing into a deplorable
stagnation, which would be otherwise inevitable in such an arduous
task.
The Conference of Lausanne and the definite Cession of
Castelrosso to Italy. The Conference of Lausanne, which after the
well-known suspension of last February resumed its proceedings on
23rd April, is slowly completing them through the no small difficulties
of various kinds caused by the delicacy and complexity of the
questions under examination. The course followed by the Italian
Delegation under any circumstance has always been inspired by the
most calm and impartial attitude, and its efficacy has been
recognised and generally appreciated at its just worth.
Italy cannot help considering as her vital interests the speedy
restoration of a normal state of trade in the East, as well as the
economic development and general progress of all the peoples living
on the shore of the Eastern Mediterranean.
Although all the questions under discussion have not yet been
solved at Lausanne, on some of them, however, which more directly
affect our country, an agreement, satisfactory on the whole, has
been reached. The Government of Angora has explicitly withdrawn
the objection regarding the cession of the island of Castelrosso to
Italy, the possession of which on our part could in no way justify an
eventual suspicion of Italian aggressive aims with regard to Turkey.
Our flag, which has already been saluted from the moment it
appeared in the island as a symbol of peaceful well-being, will in the
future continue to protect a population which by plebiscite has
entrusted itself to us.
The Juridical Protection of Foreigners in Turkey. The Italian
Government has also obtained the cancellation of those clauses, with
regard to our colonies in North Africa, which the agreements
76.
concluded after theLibyan War had left in existence, and at the
same time the interests of Libyan subjects residing in Turkey, whose
rights have been equal to those of Italian citizens, were opportunely
protected.
From the opening of the Conference the question of the juridical
protection of foreigners has been of the greatest importance. The
Conference has agreed in fixing the limits of such protection,
including it in a formula which establishes for a period of five years
the appointment on the part of the Turkish Government of foreign
judges, who are authorised to receive complaints of the sentences
and of the proceedings of Turkish magistrates.
At Lausanne there still remain under discussion certain important
questions of general interest, such as those relative to the
management of the Ottoman Public Debt and others of an economic
nature, which I hope may be quickly solved.
Relations between Italy and Russia. The present relations with
Russia are regulated by the Italo-Russian and Italo-Ukraine
Agreements of 26th December 1921. A few days ago the projects for
the conversion into law of the Royal Decree of 31st January 1922
were presented to Parliament, by whom the said agreements had
been approved, though some opposition had been offered to their
practical application. This opposition gave the Russians a pretext for
violating the agreement. We mean to remove these obstacles in
order to render easier the economic relations between the two
countries and pave the way for an understanding resting on a wider
basis without excessive illusions, but also without dangerous
prejudices.
Relations between the two countries, which possess different
economic systems, present enormous difficulties. They are, however,
not unsurmountable if on both sides there is a good-will to overcome
them. Italian policy towards Russia is clear and cannot give rise to
misunderstanding.
77.
The presentation beforeParliament of these decrees represents
another proof of our intentions and gives us the right to expect from
the Government of Moscow the scrupulous fulfilment of the pacts,
the execution of the pledge taken to abstain from any act hostile to
our Government, and from whatsoever direct or indirect propaganda
against the institutions of the kingdom.
Relations between Italy and the United States. I do not think it is
necessary, considering the brevity of this speech, to enter into
further detail. I will only say that the relations between the United
States and Italy are particularly cordial, and I am glad to add that
both the Government and the American people have fully
understood the new political situation in Italy.
Relations with Poland and other Countries. The initiative of Italy
for the definite determination of the Polish frontiers has cemented
even more closely the bonds of cordial friendship which have united
the two countries for centuries. Their collaboration continues to be
strengthened on economic as well as on political grounds. In these
last days the Polish Government has placed important orders with
Italian manufacturers.
The conversations and the personal relations I have had with the
Ministers of Austria, of Roumania, of Hungary, the recent journey of
H.M. the King of England, the commercial treaties concluded and to
be concluded, are other signs of that progressive revaluation of our
diplomatic position which I referred to at the beginning of this
speech.
Improvement of the Diplomatic and Consular Services. The
Fascista Government, always with the object of this revaluation, as
soon as it came into power instructed its representatives abroad to
direct their policy outside the confines of the country to the renewed
life of Italy, and to face immediately the problem of the means and
78.
the men forthat end. In fact, the administration of Foreign Affairs, in
the face of so many difficulties from outside, already possessed a
great difficulty in her own constitution, due to the scanty number of
its elements. The tools of our work, which is so delicate abroad, had
to be renewed, and rendered suitable, as regards the increase in
number of officials and the new conditions of Italy, for the
momentous task which they are required to perform.
Instructions have, therefore, been given with effect from the first
days of November for the reorganisation of the competition for the
Diplomatic and Consular Services, and for Interpreters.
In conclusion I wish to repeat that Italian foreign policy, while it
intends to safeguard national interests, wants at the same time to
constitute a factor of equilibrium and peace in Europe, and by such a
policy I think I interpret the tendencies and the needs of the Italian
people. (Applause.)
79.
“THE INTERNAL POLICY”
Speechdelivered at the Senate on 8th June 1923, after the one on Foreign Policy
(see p. 293).
Honourable Senators,—The problems of public order are problems
of the authority of the State. There is no real authority in the State if
public order is not perfectly normal. Public order and authority of the
State are, therefore, two aspects of the same problem. I ask you if
conditions have improved or become worse since last October.
(“Improved!”) Some of you give an affirmative answer. I, too, say
they have improved. Although, naturally, I am far from being
pessimistic and, therefore, from being discontented, I feel that
nothing ever goes well enough. But, Gentlemen, when one speaks of
public order, one must make comparisons. Even if they are
disagreeable, they are necessary. Unrest, uneasiness and sedition
are phenomena to be found not only in Italy. If we glance beyond
our frontiers we have reason to repeat that, if Messene weeps,
Sparta does not laugh! Look at the vanquished peoples and note
what happens in Austria and in Germany. Look at the victorious
peoples and you will see that only yesterday there was a strike of
public officials in Belgium, which has cost the Treasury hundreds of
millions of francs. If, then, you glance at the neutral countries, at
Spain, you will find there, too, that life is not excessively bright and
easy. All this I say for those who, at every small revolver shot fired in
one of the twenty thousand villages of Italy, think they have been
wounded by a 17–inch shell!
A Significant Comparison. But, above all, it is worth while to look
at Italy and consider, on one side, her conditions in the years 1918–
80.
20 and inthe period following 1920–21. The dominating events of
the former two years are the occupation of the factories, the
permanent strike of the officials belonging to public organisations,
carried out in rotation, and by a displacement of all the powers of
State authority (Assent.); and, although the incident is extremely
painful, one must recall to mind that in the rank and file of that
same glorious army of ours occurred an episode at Ancona which
proves how deeply sedition had worked its way into the body of the
Italian State.
The dominating event of the following two years is the punitive
Fascista expedition. Fascisti, from sheer necessity, went out to the
assault of the towns in large armed bodies. To-day all this is over.
To-day the officials of public organisations do not and will not strike.
(Assent.) When the Fascista employees of the Post and Telegraph
Offices came to me to protest because my colleague, the Hon.
Colonna di Cesaro, had punished them, I told them that if I had
been Minister of Post and Telegraphs I should have punished them
twice, and I added that, just because they were Fascisti, they would
have to recognise the necessity for a strict discipline. (Assent.)
The State renewed. The conditions of public order reached their
zenith of disintegration during the latter part of the year. In August
there was the anti-Fascista strike, which completely paralysed the
State. This had no effect; the Fascista forces, in its stead, obtained
success. And, from that time, I said that the two must be made one,
and that since that State was destitute of all the attributes of virility,
while there was a State in power which was rising with great
strength and capable of imposing discipline on the nation, it was
indispensable for the rising State to substitute itself, by a
revolutionary movement, for the other State which was declining.
The August anti-Fascista strike was followed by the Fascista
occupation of the towns of Bologna and Bolzano. The authority of
the State was a complete ruin. There are no more reports of labour
conflicts in the papers now.
81.
The Chamber andthe Conflicts. I am sufficiently impartial to say
that in these last days there has been a slight recrudescence of
trouble. What is its cause? I tell you quite frankly: the reopening of
the Chamber. (Laughter.) The Chamber is the place of questions. By
the spectacle it offers to the nation it sows seeds of conflict and
discord amongst the impulsive and excitable masses.
Further, the attitude of a section of Italian Liberalism is a very
welcome piece of good fortune for the subversive elements, because
they constitute for them unhoped-for, unexpected allies, who blow
enormous bubbles, which I promise myself to prick with the pin of
logic and sincerity before closing my speech. (Assent.) Then perhaps
there is this, that certain gentlemen, when they found out that they
had not to fear the law of Fascismo or that of the Government,
which is slower because it is bound to move in accordance with legal
procedure, resumed their bold attitude.
Elimination of the Subversive Elements. The measures adopted to
restore public order are: First of all the elimination of the so-called
subversive elements. There was much clamour after the hauling in
of the nets, but in reality it was only a very small affair. Of two
thousand who were arrested, those who are still in gaol do not reach
the figure of one hundred and fifty. They are in the hands of the
judges. They were elements of disorder and subversion. On the
morrow of each conflict I gave the categorical order to confiscate
the largest possible number of weapons of every sort and kind. This
confiscation, which continues with the utmost energy, has given
satisfactory results. (Assent.) I had to repress every illegal act.
The High Grades of the National Militia. There was another
problem with regard to the National Militia: namely the necessity of
filling the superior posts, to which had to be appointed men coming
from the army with a large personal military experience; this
necessity had to be harmonised with the gratitude due to the small
heads of Fascista “squadrismo,” the body which, by leaving
82.
thousands of gloriousdead, had crushed the subversive demagogic
elements.
We have solved this problem. All the ranks of superior officers
above those of “Seniore” have been assigned to the officers coming
from the regular army; all the inferior grades and those of sub-
officers have been given to military men, to “squadristi” who had
previously seen military life.
Moreover, statistics are always worth more than speeches. Ninety-
seven per cent. of the officers of the Militia having a rank superior to
that of “Seniore” come from the officers of the regular army. Out of
about two hundred and thirty officers superior to the rank of
“Seniore,” six are decorated with the Military Order of Savoy, two
with Gold Medals, one hundred and thirty with Silver Medals, eighty
with Bronze Medals.
As this is a day of explanations, even at the risk of abusing your
patience, I must read the list of rewards bestowed on the Chiefs of
the National Militia. General Cesare De Bono, Field Marshal of the
regular army: three Silver Medals, special promotion for war
services, “Croce di Guerra.” General Gandolfo, Field Marshal of the
regular army: two Silver Medals, special promotion for war services.
Hon. Cesare Maria De Vecchi: four Silver Medals, two Bronze Medals,
two “Croci di Guerra.” Italo Balbo: one Silver Medal, one “Croce di
Guerra.” Gustavo Fara, the general well known through all Italy: one
Gold Medal, two Silver Medals, special promotions for war services.
Stringa, Major-General of the regular army: three Silver Medals, one
Bronze Medal, disabled in the war. Ozol Clemente, Major-General in
the regular army: two Silver Medals, “Croce di Guerra.” Ceccherini,
Major-General in the regular army: three Silver Medals, two Bronze
Medals. Zambon, Major-General of the regular army: Silver Medal
and Bronze Medal. Guglielmotti, Major-General of the regular army:
two Silver Medals.
After these follow:
Giuriati, with two Silver Medals; Acerbo, with three Silver Medals
(voices: “Bravo!”); Caradonna, with three Silver Medals; Finzi, with a
83.
Silver Medal andtwo “Croci di Guerra.”
Not to embarrass the modesty of my friends, I shall not continue
to read the list of these officers of the National Militia,—(Laughter.)—
but this is enough to prove to you that this is a serious institution.
And I add that every day it becomes more so, because I mean that
it shall be so, because all its chiefs mean it.
It might be asked of us: “Why does the Militia remain?” I shall tell
it to you at once: for a very simple reason, to defend Fascismo at
home and also abroad. The word “abroad” might alarm you. Well, I
tell you that abroad there is a difficult atmosphere for Italian
Fascismo. Difficult for the parties of the Right, which, being formed
of national elements, cannot feel enthusiasm for a movement that
exalts our national qualities; difficult for the parties of the Left,
because those elements are our adversaries from the social point of
view, knowing that the Fascista movement is clearly anti-Socialist. It
is well, therefore, that it should be known that there is in Italy a
mighty army of volunteers to defend that special form of political
organisation called Fascismo.
The Militia, moreover, has the object of enabling the army to do its
own work. The army must fight, must get ready for war. It must not
do police work, especially of a political nature, except under
absolutely exceptional circumstances, of which now I do not wish to
think, even hypothetically. As an example I can tell you that last
night, upon my personal instructions, a whole section of Leghorn
was blockaded. Well, one hundred carabineers and three hundred
black shirts sufficed, whilst the army, the official troops, were
sleeping peacefully in their barracks, as was their duty and their
right. Moreover, believe me, so long as in Italy they know that,
besides some tens of thousands of faithful carabineers, there is this
enormous force, attempts at revolt or at sedition will never be dared.
Modifications to the Statute Law. Finally, and this is a manœuvre
of the last few days, have burst forth in Italy the bold defenders of
the Statute, of Liberty and of Parliament. (Laughter.) It seems,
84.
Welcome to OurBookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com