SlideShare a Scribd company logo
Visit https://ebookfinal.com to download the full version and
explore more ebooks
Programming Python with CD 2nd Edition Mark Lutz
_____ Click the link below to download _____
https://ebookfinal.com/download/programming-python-
with-cd-2nd-edition-mark-lutz/
Explore and download more ebooks at ebookfinal.com
Here are some suggested products you might be interested in.
Click the link to download
Beginning Programming With Python For Dummies 1st Edition
John Paul Mueller
https://ebookfinal.com/download/beginning-programming-with-python-for-
dummies-1st-edition-john-paul-mueller/
Distributed Programming with Ruby 1st Edition Mark Bates
https://ebookfinal.com/download/distributed-programming-with-ruby-1st-
edition-mark-bates/
Introduction to Computation and Programming Using Python
with Application to Understanding Data 2nd edition Edition
Guttag
https://ebookfinal.com/download/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-2nd-
edition-edition-guttag/
Hacking Secret Ciphers with Python A beginner s guide to
cryptography and computer programming with Python 1st
Edition Al Sweigart
https://ebookfinal.com/download/hacking-secret-ciphers-with-python-a-
beginner-s-guide-to-cryptography-and-computer-programming-with-
python-1st-edition-al-sweigart/
Active Grammar Level 3 with Answers and CD ROM 1st Edition
Mark Lloyd
https://ebookfinal.com/download/active-grammar-level-3-with-answers-
and-cd-rom-1st-edition-mark-lloyd/
Black Hat Python Python Programming For Hackers And
Pentesters 2nd Edition Justin Seitz And Tim Arnold
https://ebookfinal.com/download/black-hat-python-python-programming-
for-hackers-and-pentesters-2nd-edition-justin-seitz-and-tim-arnold/
Programming Google App Engine with Python Build and Run
Scalable Python Apps on Google s Infrastructure 1st
Edition Dan Sanderson
https://ebookfinal.com/download/programming-google-app-engine-with-
python-build-and-run-scalable-python-apps-on-google-s-
infrastructure-1st-edition-dan-sanderson/
Expert Python Programming 1st Edition Tarek Ziade
https://ebookfinal.com/download/expert-python-programming-1st-edition-
tarek-ziade/
Deep Learning with Python 2nd Edition François Chollet
https://ebookfinal.com/download/deep-learning-with-python-2nd-edition-
francois-chollet/
Get Programming Python with CD 2nd Edition Mark Lutz free all chapters
Programming Python with CD 2nd Edition Mark Lutz
Digital Instant Download
Author(s): Mark Lutz
ISBN(s): 9780596000851, 0596000855
Edition: 2
File Details: PDF, 6.98 MB
Year: 2001
Language: english
Programming Python, 2nd Edition, O’Reilly
IT-SC book 1
Programming Python, 2nd Edition
Mark Lutz
Publisher: O'Reilly
2nd Edition March 2001
ISBN: 0-596-00085-5, 1256 pages
Programming Python focuses on advanced applications of
Python. Endorsed by Python creator Guido van Rossum, it
demonstrates advanced Python techniques, and addresses
software design issues such as reusability and object-
oriented programming. The enclosed platform-neutral CD-
ROM (view CD-ROM content online at
http://examples.oreilly.com/python2) has book examples
and various Python-related packages, including the full
Python Version 2.0 source code distribution.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 2
Enjoy the life together.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 3
Foreword
Preface
"And Now for Something Completely Different . . . Again"
Signs of the Python Times
Why This Edition?
Major Changes in This Edition
Using the Examples and Demos
Conventions Used in This Book
Where to Look for Updates
Contacting O'Reilly
Acknowledgments
1. Introducing Python
1.1 "And Now for Something Completely Different"
1.2 The Life of Python
1.3 The Compulsory Features List
1.4 What's Python Good For?
1.5 What's Python Not Good For?
I: System Interfaces
2. System Tools
2.1 "The os.path to Knowledge"
2.2 Why Python Here?
2.3 System Scripting Overview
2.4 The sys Module
2.5 The os Module
2.6 Script Execution Context
2.7 Current Working Directory
2.8 Command-Line Arguments
2.9 Shell Environment Variables
2.10 Standard Streams
2.11 File Tools
2.12 Directory Tools
3. Parallel System Tools
3.1 "Telling the Monkeys What to Do"
3.2 Forking Processes
3.3 Threads
3.4 Program Exits
3.5 Interprocess Communication
3.6 Pipes
3.7 Signals
3.8 Launching Programs on Windows
3.9 Other System Tools
4. Larger System Examples I
4.1 "Splits and Joins and Alien Invasions"
4.2 Splitting and Joining Files
4.3 Generating Forward-Link Web Pages
4.4 A Regression Test Script
4.5 Packing and Unpacking Files
Programming Python, 2nd Edition, O’Reilly
IT-SC book 4
4.6 User-Friendly Program Launchers
5. Larger System Examples II
5.1 "The Greps of Wrath"
5.2 Fixing DOS Line Ends
5.3 Fixing DOS Filenames
5.4 Searching Directory Trees
5.5 Visitor: Walking Trees Generically
5.6 Copying Directory Trees
5.7 Deleting Directory Trees
5.8 Comparing Directory Trees
II: GUI Programming
6. Graphical User Interfaces
6.1 "Here's Looking at You, Kid"
6.2 Python GUI Development Options
6.3 Tkinter Overview
6.4 Climbing the GUI Learning Curve
6.5 The End of the Tutorial
6.6 Python/Tkinter for Tcl/Tk Converts
7. A Tkinter Tour, Part 1
7.1 "Widgets and Gadgets and GUIs, Oh My!"
7.2 Configuring Widget Appearance
7.3 Toplevel Windows
7.4 Dialogs
7.5 Binding Events
7.6 Message and Entry
7.7 Checkbutton, Radiobutton, and Scale
7.8 Running GUI Code Three Ways
7.9 Images
8. A Tkinter Tour, Part 2
8.1 "On Today's Menu: Spam, Spam, and Spam"
8.2 Menus
8.3 Listboxes and Scrollbars
8.4 Text
8.5 Canvas
8.6 Grids
8.7 Time Tools, Threads, and Animation
8.8 The End of the Tour
8.9 The PyDemos and PyGadgets Launchers
9. Larger GUI Examples
9.1 "Building a Better Mouse Trap"
9.2 Advanced GUI Coding Techniques
9.3 Complete Program Examples
9.4 PyEdit: A Text Editor Program/Object
9.5 PyView: An Image and Notes Slideshow
9.6 PyDraw: Painting and Moving Graphics
9.7 PyClock: An Analog/Digital Clock Widget
9.8 PyToe: A Tic-Tac-Toe Game Widget
Programming Python, 2nd Edition, O’Reilly
IT-SC book 5
9.9 Where to Go from Here
III: Internet Scripting
10. Network Scripting
10.1 "Tune in, Log on, and Drop out"
10.2 Plumbing the Internet
10.3 Socket Programming
10.4 Handling Multiple Clients
10.5 A Simple Python File Server
11. Client-Side Scripting
11.1 "Socket to Me!"
11.2 Transferring Files over the Net
11.3 Processing Internet Email
11.4 The PyMailGui Email Client
11.5 Other Client-Side Tools
12. Server-Side Scripting
12.1 "Oh What a Tangled Web We Weave"
12.2 What's a Server-Side CGI Script?
12.3 Climbing the CGI Learning Curve
12.4 The Hello World Selector
12.5 Coding for Maintainability
12.6 More on HTML and URL Escapes
12.7 Sending Files to Clients and Servers
13. Larger Web Site Examples I
13.1 "Things to Do When Visiting Chicago"
13.2 The PyMailCgi Web Site
13.3 The Root Page
13.4 Sending Mail by SMTP
13.5 Reading POP Email
13.6 Utility Modules
13.7 CGI Script Trade-offs
14. Larger Web Site Examples II
14.1 "Typos Happen"
14.2 The PyErrata Web Site
14.3 The Root Page
14.4 Browsing PyErrata Reports
14.5 Submitting PyErrata Reports
14.6 PyErrata Database Interfaces
14.7 Administrative Tools
14.8 Designing for Reuse and Growth
15. Advanced Internet Topics
15.1 "Surfing on the Shoulders of Giants"
15.2 Zope: A Web Publishing Framework
15.3 HTMLgen: Web Pages from Objects
15.4 JPython ( Jython): Python for Java
15.5 Grail: A Python-Based Web Browser
15.6 Python Restricted Execution Mode
Programming Python, 2nd Edition, O’Reilly
IT-SC book 6
15.7 XML Processing Tools
15.8 Windows Web Scripting Extensions
15.9 Python Server Pages
15.10 Rolling Your Own Servers in Python
IV: Assorted Topics
16. Databases and Persistence
16.1 "Give Me an Order of Persistence, but Hold the Pickles"
16.2 Persistence Options in Python
16.3 DBM Files
16.4 Pickled Objects
16.5 Shelve Files
16.6 SQL Database Interfaces
16.7 PyForm: A Persistent Object Viewer
17. Data Structures
17.1 "Roses Are Red, Violets Are Blue; Lists Are Mutable, and So Is Class Foo"
17.2 Implementing Stacks
17.3 Implementing Sets
17.4 Binary Search Trees
17.5 Graph Searching
17.6 Reversing Sequences
17.7 Permuting Sequences
17.8 Sorting Sequences
17.9 Data Structures Versus Python Built-ins
17.10 PyTree: A Generic Tree Object Viewer
18. Text and Language
18.1 "See Jack Hack. Hack, Jack, Hack"
18.2 Strategies for Parsing Text in Python
18.3 String Module Utilities
18.4 Regular Expression Matching
18.5 Parser Generators
18.6 Hand-Coded Parsers
18.7 PyCalc: A Calculator Program/Object
V: Integration
19. Extending Python
19.1 "I Am Lost at C"
19.2 C Extensions Overview
19.3 A Simple C Extension Module
19.4 The SWIG Integration Code Generator
19.5 Wrapping C Environment Calls
19.6 A C Extension Module String Stack
19.7 A C Extension Type String Stack
19.8 Wrapping C++ Classes with SWIG
20. Embedding Python
20.1 "Add Python. Mix Well. Repeat."
20.2 C Embedding API Overview
20.3 Basic Embedding Techniques
Programming Python, 2nd Edition, O’Reilly
IT-SC book 7
20.4 Registering Callback Handler Objects
20.5 Using Python Classes in C
20.6 ppembed: A High-Level Embedding API
20.7 Other Integration Topics
VI: The End
21. Conclusion: Python and the Development Cycle
21.1 "That's the End of the Book, Now Here's the Meaning of Life"
21.2 "Something's Wrong with the Way We Program Computers"
21.3 The "Gilligan Factor"
21.4 Doing the Right Thing
21.5 Enter Python
21.6 But What About That Bottleneck?
21.7 On Sinking the Titanic
21.8 So What's Python: The Sequel
21.9 In the Final Analysis...
21.10 Postscript to the Second Edition
A. Recent Python Changes
A.1 Major Changes in 2.0
A.2 Major Changes in 1.6
A.3 Major Changes Between 1.3 and 1.5.2
B. Pragmatics
B.1 Installing Python
B.2 Book Examples Distribution
B.3 Environment Configuration
B.4 Running Python Programs
B.5 Python Internet Resources
C. Python Versus C++
Colophon
Programming Python, 2nd Edition, O’Reilly
IT-SC book 8
Foreword
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 ever-apart 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 gray-there 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 code-even many standard library modules-imports 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 time-although 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
Programming Python, 2nd Edition, O’Reilly
IT-SC book 9
into the current Python 2.x line of development, with a clear transition path that
includes a period of backwards compatibility support.
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 3000-only 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 Life-that'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.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 10
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
"And Now for Something Completely Different . . .
Again"
The first edition of this book was one of the first to present the Python language.
This second edition is an almost completely new advanced Python topics book,
designed to be a follow-up to the core language material in Learning Python and
supplemented by the reference material in Python Pocket Reference.
That is, this edition is focused on ways to use Python, rather than on the language
itself. Python development concepts are explored along the way -- in fact, they really
become meaningful only in the context of larger examples like those in this edition.
But in general, this text now assumes that you already have at least a passing
acquaintance with Python language fundamentals, and moves on to present the rest
of the Python story.
In this preface, I'll explain some of the rationales for this major rewrite, describe the
structure of this edition in more detail, and give a brief overview of how to use the
Python programs shipped on the enclosed CD-ROM (view CD-ROM content online at
http://examples.oreilly.com/python2). First of all, though, a history lesson is in
order.
Signs of the Python Times
It's been an exciting five years in the Python world. Since I wrote the first edition of
this book between 1995 and 1996, Python has grown from a new kid on the scripting
languages block to an established and widely used tool in companies around the
world. Although measuring the popularity of an open source (http://opensource.org)
and freely distributed tool such as Python is not always easy, most statistics
available reveal exponential growth in Python's popularity over the last five years.
Among the most recent signs of Python's explosive growth:
Books
As I write this in 2001, there are now over a dozen Python books on the market,
with almost that many more on the way (in 1995 there were none). Some of these
books are focused on a particular domain (e.g., Windows), and some are available in
German, French, and Japanese language editions.
Users
In 1999, one leading industry observer suggested that there were as many as
300,000 Python users worldwide, based on various statistics. Other estimates are
more optimistic still. In early 2000, for instance, the Python web site was already on
track to service 500,000 new Python interpreter downloads by year end (in addition
Programming Python, 2nd Edition, O’Reilly
IT-SC book 11
to other Python distribution mediums); this figure is likely closer to the true user-
base size as I write this book.
Press
Python is now regularly featured in industry publications. In fact, since 1995, Python
creator Guido van Rossum has appeared on the cover of prominent tech magazines
such as Linux Journal and Dr. Dobb's Journal; the latter publication gave him a
programming excellence award for Python.[1]
[1]
As I was writing this book, Linux Journal also published a special Python
supplement with their May 2000 edition -- the cover of which, of course, featured a
naked man seated outdoors in front of a computer desk instead of a piano. If you
don't know why that is funny, you need to watch a few reruns from Python's
namesake, the Monty Python television series (consider it a first suggested exercise).
I'll say more about the implications of Python's name in the first chapter.
Applications
Real companies have adopted Python for real products. It has shown up animating
the latest Star Wars movie (Industrial Light & Magic), serving up maps and
directories on the Internet (Yahoo), guiding users through Linux operating system
installation (Red Hat), testing chips and boards (Intel), managing Internet discussion
forums (Egroups), scripting online games (Origin), talking to CORBA frameworks
(TCSI), implementing web site tools (Digital Creations' Zope), scripting wireless
products (Agilent), and much more.[2]
[2]
See http://www.python.org for more details. Some companies don't disclose their
Python use for competitive reasons, though many eventually become known when
one of their web pages crashes and displays a Python error message in a browser.
Hewlett Packard is generally counted among companies thus "outed."
Newsgroup
User traffic on the main Python Internet newsgroup, comp.lang.python, has risen
dramatically too. For instance, according to eGroups (see
http://www.egroups.com/group/python-list), there were 76 articles posted on that
list in January 1994, and 2678 in January 2000 -- a 35-fold increase. Recent months
have been busier still (e.g., 4226 articles during June, 2000 alone -- roughly 140 per
day), and growth has been constant since the list's inception. This, and all other
user-base figures cited in this preface, are likely to have increased by the time you
read this text. But even at current traffic rates, Python forums are easily busy
enough to consume the full-time attention of anyone with full-time attention to burn.
Conferences
There are now two annual Python conferences, one of which is hosted by O'Reilly &
Associates. Attendance at Python conferences has roughly doubled in size every
year. An annual Python Day is now also held in Europe.
Group therapy
Regional Python user groups have begun springing up in numerous sites in the U.S.
and abroad, including Oregon, San Francisco, Washington D.C., Colorado, Italy,
Programming Python, 2nd Edition, O’Reilly
IT-SC book 12
Korea, and England. Such groups work on Python-related enhancements, organize
Python events, and more.
Domains
Python has grown to embrace both Microsoft Windows developers, with new support
for COM and Active Scripting, as well as Java developers, with the new JPython
(renamed "Jython") Java-based implementation of the language. As we'll see in this
edition, the new COM support allows Python scripts to be both component server and
client; Active Scripting allows Python code to be embedded in HTML web page code
and run on either client or server; and JPython compiles Python scripts to Java
Virtual Machine code so that they can be run in Java-aware systems and can
seamlessly integrate Java class libraries for use by Python code. As an open source
tool for simplifying web site construction, the Python-based Zope web application
framework discussed in this edition has also begun capturing the attention of
webmasters and CGI coders.
Services
On the pragmatics front, commercial support, consulting, prepackaged distributions,
and professional training for Python are now readily available from a variety of
sources. For instance, the Python interpreter can be obtained on CDs and packages
sold by various companies (including Walnut Creek, Dr. Dobb's Journal, and
ActiveState), and Python usually comes prebuilt and free with most Linux operating
system distributions.
Jobs
It's now possible to make money as a Python programmer (without having to resort
to writing large, seminal books). As I write this book, the Python job board at
http://www.python.org/Jobs.html lists some 60 companies seeking Python
programmers in the U.S. and abroad. Searches for Python at popular employment
sites yield even more hits -- for instance, 285 Python-related jobs on Monster.com,
and 369 on dice.com. Not that anyone should switch jobs, of course, but it's nice to
know that you can now make a living by applying a language that also happens to be
a pleasure to use.
Tools
Python has also played host to numerous tools development efforts. Among the most
prominent as I write these words: the Software Carpentry project, which is
developing new core software tools in Python; ActiveState, which ison the verge of
releasing a set of Windows and Linux-focused Python development products; and
PythonWare, which is about to release an integrated Python development
environment and GUI builder.
Compilers
As I write this preface, ActiveState has also announced a new Python compiler for
the Microsoft .NET framework and C# language environment -- a true Python
compiler and independent implementation of the Python language that generates
DLL and EXE files, allows Python code to be developed under Visual Studio, and
provides seamless .NET integration for Python scripts. It promises to be a third
Programming Python, 2nd Edition, O’Reilly
IT-SC book 13
implementation of Python, along with the standard C-based Python, and the JPython
Java-based system.
Education
Python has also begun attracting the attention of educators, many of whom see
Python as a "Pascal of the 2000s" -- an ideal language for teaching programming,
due to its simplicity and structure. Part of this appeal was spawned by Guido van
Rossum's proposed Computer Programming for Everybody (CP4E) project, aimed at
making Python the language of choice for first-time programmers worldwide. At this
writing the future of CP4E itself is uncertain, but a Python special interest group
(SIG) has been formed to address education-related topics. Regardless of any
particular initiative's outcome, Python promises to make programming more
accessible to the masses of people who will surely soon grow tired of clicking
preprogrammed links, as they evolve from computer users to computer scripters.
In other words, it's not 1995 anymore. Much of the preceding list was unimaginable
when the first edition of this book was conceived. Naturally, this list is doomed to be
out of date even before this book hits the shelves, but it is nonetheless
representative of the sorts of milestones that have occurred over the last five years,
and will continue to occur for years to come. As a language optimized to address the
productivity demands of today's software world, Python's best is undoubtedly yet to
come.
So What's Python?
If you 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.
Among other things, Python sports object-oriented programming (OOP); a
remarkably simple, readable, and maintainable syntax; integration with C
components; and a vast collection of precoded interfaces and utilities.
Although general-purpose, 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.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 14
Why This Edition?
One consequence of the growing popularity of Python has been an influx of new
users, programming styles, and applications, all of which have conspired to make
parts of the first edition of this book prime for updates. Python itself has changed in
smaller ways, but important extensions have simplified various aspects of Python
development and merit new coverage.
Perhaps most relevant for this edition is that the Python "audience" has changed.
Over the last five years, Python has transitioned from an emerging language of
interest primarily to pioneers to a widely accepted tool used by programmers for
day-to-day development tasks. This edition has been refocused for this new Python
audience. You will find that it is now more of a nuts-and-bolts text, geared less
toward introducing and popularizing the language than to showing how to apply it for
realistically scaled programming tasks.
Because of the breadth of change, this edition is something of an entirely new book.
To readers who enjoyed the first edition, I would like to express my gratitude, and I
hope you will find the same spirit in this second edition. Although this is a major
rewrite, I have tried to retain as much of the original book's material and flavor as
possible (especially the jokes :-).
Since writing the first edition five years ago, I have also had the opportunity to teach
Python classes in the U.S. and abroad, and some of the new examples reflect
feedback garnered from these training sessions. The new application domain
examples reflect common interests and queries of both myself and my students.
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 edition's examples and topics.
Other new examples are simply the result of my having fun programming Python.
Yes, fun; I firmly believe that one of Python's greatest intangible assets is its ability
both to kindle the excitement of programming among newcomers, and to rekindle
the excitement among those who have toiled for years with more demanding tools.
As we will see in this edition, Python makes it incredibly easy to play with advanced
but practical tools such as threads, sockets, GUIs, web sites, and OOP -- areas that
can be both tedious and daunting in traditional compiled languages like C and C++.
Frankly, even after eight years as a bona fide Pythonista, I still find programming
most enjoyable when it is done in Python. Python is a wildly productive language,
and witnessing its application first-hand is an aesthetic delight. I hope this edition, as
much as the first, will demonstrate how to reap Python's productivity benefits and
communicate some of the satisfaction and excitement found in a rapid-development
tool such as Python.
Major Changes in This Edition
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 first edition, the next few sections go into more
detail about what is new in this edition.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 15
It's Been Updated for Python 2.0
This edition has been updated for Python 2.0, and the Graphical User Interface (GUI)
material has been updated for Tk versions 8.0 or later. Technically, this update was
begun under Python 1.5.2, but all examples were revisited for 2.0 before publication.
For the trivia buffs among you: release 2.0 was the first Python release following
Guido's move to BeOpen, while 1.6 was the last release from Guido's prior employer,
CNRI. Just before I finished this book's final draft and after the 2.0 release, Guido
and the core Python development team moved from BeOpen to Digital Creations,
home of the Zope web application construction kit, but this move is independent of
Python releases (see Chapter 1, for more details).
Release 2.0 introduces a few language extensions, but 2.0 and 1.6 are similar in
content, and the updates just add a handful of features. The examples in this book
should generally work with later Python releases. Remarkably, almost all examples in
the first edition still work five years later, with the latest Python releases; those that
didn't work required only small fixes (e.g., GUI call formats and C API interfaces).
On the other hand, although the core language hasn't changed much since the first
edition, a number of new constructs have been added, and we'll apply them all here.
Among these new Python features: module packages, class exceptions, pseudo-
private class attributes, unicode strings, the new regular expression module, new
Tkinter features such as the grid manager, standard dialogs, and top-level menus,
and so on. A new appendix summarizes all of the major changes in Python between
the first and second editions of this book.
In addition to the language changes, this book presents new Python tools and
applications that have emerged in recent years. Among them: the IDLE
programming interface, the JPython (a.k.a. "Jython") compiler, Active Scripting and
COM extensions, the Zope web framework, Python Server Pages (PSP), restricted
execution mode, the HTMLgen and SWIG code generators, thread support, CGI and
Internet protocol modules, and more (it's been a busy five years). Such applications
are the heart and soul of this second edition.
It's Been Refocused for a More Advanced Audience
This edition presents Python programming by advanced examples. Becoming
proficient in Python involves two distinct tasks: learning the core language itself, and
then learning how to apply it in applications. This edition addresses the latter (and
larger) of these tasks by presenting Python libraries, tools, and programming
techniques. Since this is a very different focus, I should say a few words about its
rationale here.
Because there were no other Python books on the horizon at the time, the first
edition was written to appeal to many audiences at once -- beginners and gurus
alike. Since then, another O'Reilly book, Learning Python, has been developed to
address the needs of beginners, and Python Pocket Reference was published for
readers seeking a short Python reference. As a result, the core language
introductory-level material and the original reference appendixes have been removed
from this book.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 16
Learning Python introduces the core language -- its syntax, datatypes, and so on --
using intentionally simplistic examples. Many have found it to be ideal for learning
the language itself, but Python can become even more interesting once you master
the basic syntax and can write simple examples at the interactive prompt. Very soon
after you've learned how to slice a list, you 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.
Programming Python focuses on the "everything else" of Python development. 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 only be illustrated in the context of
realistically scaled programs. In other words, Programming Python, especially in this
new edition, is designed to pick up where Learning Python leaves off.
Therefore, if you find this book too advanced, I encourage you to read Learning
Python as a prelude to this text, and return here for the rest of the story once you've
mastered the basics. Unless you already have substantial programming experience,
this edition might serve you best as a second Python text.
It Covers New Topics
Most of the changes in this edition were made to accommodate new topics. There
are new chapters and sections on Internet scripting, CGI scripts, operating system
interfaces, the SWIG integration code generator, advanced Tkinter topics, the
HTMLgen web page generator, JPython, threads, restricted execution mode, and
more. You should consult the Table of Contents for the full scoop, but here are some
of the new topics and structural changes you'll find in this edition:
Topics
The Internet, systems programming, Tkinter GUIs, and C integration domains get
much more attention, and are arguably now the main focus of this text. For instance,
you'll find six new chapters on Internet scripting, covering client-side tools, server-
side scripts and web sites, and advanced Internet topics and systems. Four new
chapters address systems topics: threads, directory processing, program launching,
and so on. And the GUI material has also grown from one chapter to a much more
complete four-chapter presentation, and now covers all widgets (including text and
canvas), as well as new grid, menu, and dialog support.
C integration
The C extending and embedding chapters have been expanded to cover new topics
such as SWIG (the way to mix Python with C/C++ libraries today) and present new
mixed-mode examples such as callback dispatch (extending plus embedding). C
integration is at the heart of many Python systems, but the examples in this domain
are inevitably complex, and involve large C programs that are only useful to C users.
In deference to readers who don't need to code C integrations, this material is now
isolated at the end of the text. Some of the C code listings are gone as well -- to
reduce page count, I have opted instead to point readers to C source files on the
enclosed CD-ROM where possible (see http://examples.oreilly.com/python2).
Programming Python, 2nd Edition, O’Reilly
IT-SC book 17
Although later chapters build upon material in earlier chapters, topics in this edition
are covered fairly independently, and are associated by book parts. Because of that,
it's not too much of a stretch to consider this edition to be akin to four or five books
in one. Its top-level structure underscores its application topics focus:
Preface (you are here)
Chapter 1
Part I
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Part II
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Part III
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Part IV
Chapter 16
Chapter 17
Chapter 18
Part V
Chapter 19
Chapter 20
Part VI
Chapter 21
Appendix A
Appendix B
Appendix C
Two notes here: First of all, don't let these titles fool you -- although 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. Second, readers who
use Python as a standalone tool can safely skip the integration chapters, though I
still recommend a quick glance. C programming isn't nearly as fun or easy as Python
programming. 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.
First edition readers will notice that most of this material is new, and even chapters
with old titles contain largely new material. Noticeably absent in this edition are the
original Sneak Preview, Mini Reference, Tutorial Appendix, and all of the old Part II --
a reflection of the new focus and intended readership.
It's More Example-Oriented
Programming Python, 2nd Edition, O’Reilly
IT-SC book 18
This book is largely about its examples. In this edition, old examples have been
extended to become more realistic (e.g., PyForm and PyCalc), and new examples
have been added throughout. Among the major examples, you'll find:
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
A tree data structure 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
PyMail
A Python/Tk POP and SMTP email client
PyFtp
A simple Python/Tk file-transfer GUI
PyErrata
A web-based error report system
PyMailCgi
A web-based email interface
Programming Python, 2nd Edition, O’Reilly
IT-SC book 19
There are also new 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 new socket and select module examples), many new
examples of Python threads, and new coverage of JPython, HTMLgen, Zope, Active
Scripting, COM, and Python database interfaces. Many of the new examples are
somewhat advanced, but of course this is now a somewhat advanced text.
In addition, the old Python/C embedding API (now called ppembed ) has been
extended to support precompiling strings to bytecode, and the original calculator
example (now called PyCalc) has been beefed up to support keyboard entry, history
lists, colors, and more.
In fact, the new book examples tree distributed on this edition's CD-ROM (see
http://examples.oreilly.com/python2) is itself a fairly sophisticated Python software
system, and the examples within it have been upgraded structurally in a number of
important ways:
Examples tree
The entire examples distribution has been organized as one big Python module
package to facilitate cross-directory imports and avoid name-clashes with other
Python code installed on your computer. Using directory paths in 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 PP2E examples root directory. To reuse code in this book within your
own applications, simply import through the PP2E package root (e.g., from
PP2E.Launcher import which).
Example filenames
Module names are generally much less cryptic now. I punted on 8.3 DOS
compatibility long ago, and use more descriptive filenames. I've also fixed some old
all-uppercase filenames, which were a last vestige of MS-DOS.
Example titles
Labels of example listings now 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:
PP2EInternetFtpsousa.py refers to the file sousa.py in the PP2EInternetFtp
subdirectory of the examples distribution directory.[4]
[4]
The "examples distribution directory" is the directory containing the top-level PP2E
directory of the book examples tree. On the CD (see
http://examples.oreilly.com/python2), it's the topmost Examples directory; if you've
copied the examples to your machine, it's wherever you copied (or unpacked) the
PP2E root directory. You can run most of the examples from the CD directly, but
you'll want to copy them to your hard drive to make changes, and to allow Python to
save .pyc compiled bytecode files for quicker startups.
Example command lines
Programming Python, 2nd Edition, O’Reilly
IT-SC book 20
Similarly, when a command line is shown typed after a prompt such as
C:...PP2ESystemStreams>, for example, it is really to be typed in the
PP2ESystemStreams subdirectory in your examples tree. Unix and Linux users:
please think / when you see  in filename paths (my official excuse for which is
outlined in the next section).
Example launchers
Because it's just plain fun to click on things right away, there are new self-
configuring demo launcher programs (described later in this preface in Section
P.5.1), to give you a quick look at Python scripts in action with minimal configuration
requirements. You can generally run them straight off the book's CD without setting
any shell variables first.
It's More Platform-Neutral
Except for some C integration examples, the majority of the programs in this edition
were developed on my Windows 98 laptop, 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 Red Hat Linux 6.x platform only if they exercise Unix-specific interfaces.
This is not a political statement at all -- I like Linux too. It's mostly a function of the
fact that I wrote this book with MS Word; when time is tight, it's more convenient to
run scripts on the same platform as your publishing tools than to frequently reboot
into Linux. Luckily, because Python has now become so portable to both Windows
and Linux, the underlying operating system is less of a concern to Python developers
than it once was. Python, its libraries, and its Tkinter GUI framework all work
extremely well on both platforms today.
Because I'm not a politician, though, I've tried to make the examples as platform-
neutral as possible, and point out platform-specific issues along the way. Generally
speaking, most of the scripts should work on common Python platforms unchanged.
For instance, all the GUI examples were tested on both Windows (98, 95) 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 generally
built to be portable, this is easier than it may sound.
On the other hand, this book does delve into platform-specific topics where
appropriate. There is new coverage of many Windows-specific topics -- Active
Scripting, COM, program launch options, and so on. Linux and Unix readers will also
find material geared towards their platforms -- forks, pipes, and the like. There is
also new discussion of ways to edit and run Python programs on most major
platforms.
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-biased. One can at least make a reasonable
case for such a focus -- not only does Linux come with C compilers for free, but its
development environment grew up around that language. On Windows, the C
extension code shown in this book will work, but you may need to use different build
Programming Python, 2nd Edition, O’Reilly
IT-SC book 21
procedures that vary per Windows compiler. O'Reilly has published an outstanding
text, Python Programming on Win32, that covers Windows-specific Python topics like
this, and should help address some of the disparity here. If you do Windows-specific
programming, please see that book for all Windows details skipped here.
But It's Still Not a Reference Manual
Please note that 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 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 contents. For
an exhaustive list of all tools available in the Python system, consult other
books (e.g., O'Reilly's Python Pocket Reference) or the standard manuals at
Python's web site and on this book's CD-ROM (see
http://examples.oreilly.com/python2).
Using the Examples and Demos
I want to briefly describe how to use the book's examples here. In general, though,
please see the following text files in the examples distribution directory for more
details:
README-root.txt: package structure notes
PP2EREADME-PP2E.txt: general usage notes
PP2EConfigsetup-pp.bat: Windows configuration
PP2EConfigsetup-pp.csh: Unix and Linux configuration
Of these, the README-PP2E.txt file is the most informative, and the PP2EConfig
directory contains all configuration file examples. I give an overview here, but the
files listed give a complete description.
The Short Story
If you want to see some Python examples right away, do this:
Install Python from the book's CD-ROM (see http://examples.oreilly.com/python2),
unless it is already installed on your computer. On Windows, click on the name of the
self-installer program on the CD and do a default install (say "yes" or "next" to every
prompt). On other systems, see the README file (the gzipped source distribution on
the CD can be used to build Python locally).
Programming Python, 2nd Edition, O’Reilly
IT-SC book 22
Start one of the following self-configuring scripts located in the top-level
ExamplesPP2E directory on the CD (see http://examples.oreilly.com/python2).
Either click on their icons in your file explorer, or run them from your system prompt
(e.g., DOS console box, Linux Xterm) using command lines of the form python
script-name (you may need to use the full path to python if it's not 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 standard Python/Tk utilities
LaunchBrowser.py: opens web examples index in web browser
The Launch_* scripts start Python programs portably[5]
and require only that Python
be installed -- you don't need to set environment variables first or tweak the
included PP2EConfig setup files 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).
[5]
All the demo and launcher scripts are written portably but are known to work only on
Windows 95/98 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, X11, and Macs; Python itself runs on everything from handheld PDAs to
mainframes; and my advance for writing this book wasn't as big as you may think.
If installing Python isn't an option, you can still run a few Python web demos by
visiting http://starship.python.net/~lutz/PyInternetDemos.html with your browser.
Because these examples execute scripts on a server, they tend to work best when
run live from this site, rather than from the book's CD.
The Details
To help organize the new examples, I've provided a demo launcher program,
PyDemos.pyw, in the top-level PP2E directory of the examples distribution. Figure P-
1 shows PyDemos in action on Windows after pressing a few buttons. The launcher
bar appears on the left of the screen; with it, you can run most of the major
graphical examples in the book with a mouse click. The demo launcher bar can also
be used to start major Internet book examples if a browser can be located on your
machine (see the following launcher description).
Besides launching demos, the PyDemos source code provides pointers to major
examples in the distribution; see its source code for details. You'll also find Linux
automated build scripts for the Python/C integration examples in the top-level
examples directory, which serve as indexes to major C examples.
Figure P-1. The PyDemos launcher with pop-ups and demos (Guido's photo
reprinted with permission from Dr. Dobb's Journal)
Programming Python, 2nd Edition, O’Reilly
IT-SC book 23
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 often; configure as
desired). Figure P-2 shows what PyGadgets_bar looks like on Windows, along with a
few of the utilities that its buttons can launch. All of the programs are presented in
this book and included in the examples distribution. Most gadgets require a Python
with Tkinter support, but that is the default configuration for the standard Windows
port on the book's CD (see http://examples.oreilly.com/python2).
Figure P-2. The PyGadgets utilities launcher bar, with gadgets
Programming Python, 2nd Edition, O’Reilly
IT-SC book 24
To run the files listed in the prior paragraph directly, you'll need to set up your
Python module search path (see the top-level PP2E/Config/setup* files for hints).
But if you want to run a collection of Python demos from the book and don't want to
bother with setting up your environment first, simply run the self-launching utility
scripts in the PP2E directory instead: Launch_PyDemos.pyw, Launch_PyGadgets.py,
and Launch_PyGadgets_bar.pyw.
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 the
demos. You can probably run these launch scripts by simply clicking on their names
in a file explorer, and you should also be able to run them directly from the book's
CD-ROM (see http://examples.oreilly.com/python2). See the comments at the top of
Launcher.py for more details (or read about these scripts in Chapter 4 ).
Many of the browser-based Internet examples from the book can also be found
online at http://starship.python.net/~lutz/PyInternetDemos.html, where you can
test-drive a few Python Internet scripting examples. Because these examples run in
your web browser, they can be tested even if you haven't installed Python (or
Python's Tk support) on your machine.
The PyDemos program also attempts to launch a web browser on the major example
web pages by starting 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. Provided LaunchBrowser can find a
browser on your machine, some demo buttons will pop up web pages automatically,
whether you have a live Internet connection or not (if not, you'll see local files in
your browser). Figure P-3 shows what the PyInternetDemos page looks like under
Internet Explorer on Windows.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 25
Figure P-3. The PyInternetDemos web page
Of special interest, the getfile.html link on this page allows you to view the source
code of any other file on the book's site -- HTML code, Python CGI scripts, and so on;
see Chapter 12 for details. To summarize, here is what you'll find in the top-level
PP2E directory of the book's examples distribution:
PyDemos.pyw
Button bar for starting major GUI and Internet examples
PyGadgets.py
Starts programs in non-demo mode for regular use
PyGadgets_bar.pyw
Button bar for starting PyGadgets on demand
Launch_*.py*
Starts PyDemos and PyGadgets programs using Launcher.py to autoconfigure search
paths (run these for a quick look)
Launcher.py
Programming Python, 2nd Edition, O’Reilly
IT-SC book 26
Used to start programs without environment settings -- finds Python, sets
PYTHONPATH, spawns Python programs
LaunchBrowser.py
Opens example web pages with an automatically located web browser, either live off
the Net or by opening local web page files; if started directly, opens the
PyInternetDemos index page
There are also subdirectories for examples from each major topic area of the book.
In addition, the top-level PP2EPyTools 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 the book's CD (see http://examples.oreilly.com/python2),
deleting old .pyc bytecode files in the tree, and more. Again, see the distribution's
README-PP2E.txt file for more details on all example issues.
Where It's At
The book examples distribution can be found on the CD-ROM that accompanies this
book. See the CD's top-level README file for usage details, or browse the CD's
example root directory in your favorite file explorer for a quick tour.
In addition to the book examples, the CD also contains various Python-related
packages, including a full Windows self-installer program with Python and Tk support
(double-click and say "yes" at all prompts to install), the full Python source code
distribution (unpack and compile on your machine), and Python's standard
documentation set in HTML form (click to view in your web browser).
Extra open source packages such as the latest releases (at the time of publication) of
the SWIG code generator and JPython are also included, but you can always find up-
to-date releases of Python and other packages at Python's web site,
http://www.python.org.
Conventions Used in This Book
The following font conventions are used in this book:
Italic
Used for file and directory names, commands, 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
Programming Python, 2nd Edition, O’Reilly
IT-SC book 27
Constant width italic
Used to mark replaceables
This icon designates a note related to the nearby text.
This icon designates a warning related to the nearby text.
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 second edition's link on
that page for all supplemental information related to this version of the book. As for
the first edition, I will also be maintaining a log on this web site of Python changes
over time, which you should consider a supplement to this text.
Beginning with this edition, I am making available a user-driven book errata
reporting system on the World Wide Web, at this site:
http://starship.python.net/~lutz/PyErrata/pyerrata.html
There, you'll find forms for submitting book problem reports and comments, as well
as viewing the report database by various sort keys. Reports are stored in a publicly
browsable database by default, but an option lets you email them privately instead.
The PyErrata system also happens to be written in Python, and is an example
presented and shipped with this book; see Chapter 14. Figure P-4 shows what the
root page of PyErrata looks like.
Figure P-4. The PyErrata book updates site
Programming Python, 2nd Edition, O’Reilly
IT-SC book 28
If any of these addresses stop working over time, these pages might also be
accessible from O'Reilly's web site, http://www.oreilly.com.[6]
I'm still happy to
receive direct emails from readers, of course, but the PyErrata site will hopefully
streamline the report-posting process.
[6]
O'Reilly has an errata report system at their site too, 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 & Associates, Inc.
101 Morris Street
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (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:
http://www.oreilly.com/catalog/python2/
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
Programming Python, 2nd Edition, O’Reilly
IT-SC book 29
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
Programming Python, 2nd Edition, O’Reilly
IT-SC book 30
Acknowledgments
In addition to the people I mentioned in the first edition's preface, I'd like to extend
appreciation to a few of the people who helped in some way during this second
edition project:
To this book's first editor, Frank Willison, for overseeing this update, as well as
championing the Python cause at O'Reilly and beyond. To this book's later editor,
Laura Lewin, for picking up the ball and lighting necessary fires.
To Python creator Guido van Rossum for making this stuff fun again.
To the people who took part in a review of an early draft of this edition: Eric
Raymond, Mark Hammond, David Ascher, Tim Peters, and Dave Beazley.
To Tim O'Reilly and the staff of O'Reilly & Associates, both for producing this book,
and supporting open source software in general.
To the Python community at large, for diligence, hard work, and humor -- both in the
early years and today. We've come far, but to steal a line from the 1970s: You aint'
seen nothin' yet.
And to the students of the many Python classes I have taught, as well as the scores
of readers who took the time to send me comments about the first edition; your
opinions helped shape this update.
Finally, a few personal notes of thanks. To my children, Michael, Samantha, and
Roxanne, for purpose. If they are at all representative of their generation, the future
of our species seems in very good hands. You'll have to pardon me if that sounds
proud; with kids like mine, it's impossible to feel otherwise.
And most of all to Lisa, the mother of those amazing kids. I owe her my largest debt
of gratitude, for everything from enduring my flights from reality while writing books
like this, to keeping me out of jail in our youth. No matter what the future may hold,
I'll always be glad that something threw us together two decades ago.
Mark Lutz
November 2000
Somewhere in Colorado
"When Billy Goes Down, He's Going
Down Fast"
The last five years have also been host to the rise of the open source
movement. Open source refers to software that is distributed free of charge
with full source code, and is usually the product of many developers working
in a loosely knit collaborative fashion. Python, the Linux operating system,
and many other tools such as Perl and the Apache web server fall into this
category. Partly because of its challenge to the dominance of mega-
companies, the open source movement has quickly spread through society
Programming Python, 2nd Edition, O’Reilly
IT-SC book 31
in profound ways.
Let me tell you about an event that recently underscored the scope of this
movement's impact on me. To understand this story, you first need to know
that as I was writing this book, I lived in a small town in Colorado not
generally known for being on the cutting edge of technological innovation.
To put that more colorfully, it's the sort of place that is sometimes called a
"cowboy town."
I was at a small local bookstore hunting for the latest Linux Journal. After
browsing for a while, I found a copy and walked it to the checkout. Behind
the counter were two clerks who looked as if they might be more at home at
a rodeo than behind the counter of this establishment. The older of the two
sported gray hair, a moustache, and the well-worn skin of a person
accustomed to life on a ranch. Both wore obligatory baseball caps. Cowboys,
to be sure.
As I put the magazine down, the elder clerk looked up for a moment, and
said, in classic cowboy drawl, "Linux, huh? I tell you what, when Billy goes
down, he's goin' down fast!" Of course, this was in reference to the widely
publicized competition between Linux and Bill Gates' Microsoft Windows,
spurred by the open source movement.
Now, in another time and place, these two might have instead been
discussing livestock and firearms over strong cups of coffee. Yet somehow,
somewhere, they had become passionate advocates of the Linux open
source operating system. After collecting my chin from the floor, we wound
up having a lively discussion about Linux, Microsoft, Python, and all things
open. You might even say we had a good-old time.
I'm not trying to express a preference for one operating system over
another here; both have merits, and Python runs equally well on either
platform (indeed, this book's examples were developed on both systems).
But I am amazed that an idea that software developers often take for
granted has had such a deep, mainstream impact. That seems a very
hopeful thing to me; if technology is to truly improve the quality of life in
the next millennium, we need all the cowboys we can get.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 32
Chapter 1. Introducing Python
1.1 "And Now for Something Completely
Different"
1.2 The Life of Python
1.3 The Compulsory Features List
1.4 What's Python Good For?
1.5 What's Python Not Good For?
1.1 "And Now for Something Completely Different"
This book is about using Python, a very high-level, object-oriented, open source[1]
programming language, designed to optimize development speed. Although it is
completely general-purpose, Python is often called an object-oriented 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.
[1]
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
half a million users in that community today, Python is very well supported.
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 nontechnical 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 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:
Quality
Python makes it easy to write software that can be reused and maintained. It was
deliberately designed to raise development quality expectations in the scripting
world. Python's clear syntax and coherent design almost forces programmers to
write readable code -- a critical feature for software that may be changed by others.
The Python language really does look like it was designed, not accumulated. Python
is also well tooled for modern software reuse methodologies. In fact, writing high-
quality Python components that may be applied in multiple contexts is almost
automatic.
Productivity
Programming Python, 2nd Edition, O’Reilly
IT-SC book 33
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 lower-
level languages. Things like type declarations, memory management, and build
procedures are nowhere to be found in Python scripts. 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 long after they have been written. In addition, Python
supports (but does not impose) advanced paradigms such as object-oriented
programming, which further boost developer productivity and shrink development
schedules.
Portability
Most Python programs run without change on almost every computer system in use
today. In fact, Python programs run today on everything from IBM mainframes and
Cray Supercomputers to notebook PCs and handheld PDAs. Although some platforms
offer nonportable extensions, the core Python language and libraries are platform-
neutral. For instance, most Python scripts developed on Linux will generally run on
Windows immediately, and vice versa -- simply copy the script over. Moreover, a
graphical user interface (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 at
all.
Integration
Python is designed to be integrated with other tools. Programs written in Python can
be easily mixed with and script (i.e., direct) other components of a system. Today,
for example, Python scripts can call out to existing C and C++ libraries, talk to Java
classes, integrate with COM and CORBA components, 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 servers, and so on. Python is
not a closed box.
In an era of increasingly short development schedules, faster machines, and
heterogeneous applications, these strengths have proven to be powerful allies 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, libraries of precoded tools to minimize up-front development, and
completely free nature that cuts product development and deployment costs.
But Python's productivity focus is perhaps its most attractive and defining quality. As
I write this, the main problem facing the software development world is not just
writing programs quickly, but finding developers with time to write programs at all.
Developers' time has become paramount -- much more critical than execution speed.
There are simply more projects than programmers to staff them.
As a language optimized for developer productivity, Python seems to be the right
answer to the questions being asked by the development world. Not only can Python
developers implement systems quickly, but the resulting systems will be
maintainable, portable, and easily integrated with other application components.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 34
1.2 The Life of Python
Python was invented around 1990 by Guido van Rossum, when he was at CWI in
Amsterdam. Despite the reptiles, it is named after the BBC comedy series Monty
Python's Flying Circus, of which Guido is a fan (see the following silly sidebar). Guido
was also involved with the Amoeba distributed operating system and the ABC
language. In fact, the original motivation for Python was to create an advanced
scripting language for the Amoeba system.
But Python's design turned out to be general enough to address a wide variety of
domains. It's now used by hundreds of thousands of engineers around the world, in
increasingly diverse roles. Companies use Python today in commercial products, for
tasks such as testing chips and boards, developing GUIs, searching the Web,
animating movies, scripting games, serving up maps and email on the Internet,
customizing C++ class libraries, and much more.[2]
In fact, because Python is a
completely general-purpose language, its target domains are only limited by the
scope of computers in general.
[2]
See the preface for more examples of companies using Python in these ways, and see
http://www.python.org for a more comprehensive list of commercial applications.
Since it first appeared on the public domain scene in 1991, Python has continued to
attract a loyal following, and spawned a dedicated Internet newsgroup,
comp.lang.python, in 1994. And as the first edition of this book was being written in
1995, Python's home page debuted on the WWW at http://www.python.org -- still
the official place to find all things Python.
What's in a Name?
Python gets its name from the 1970s British TV comedy series, Monty
Python's Flying Circus. According to Python folklore, Guido van Rossum,
Python's creator, was watching reruns of the show at about the same time
he needed a name for a new language he was developing. And, as they say
in show business, "the rest is history."
Because of this heritage, references to the comedy group's work often show
up in examples and discussion. For instance, the name "Spam" has a special
connotation to Python users, and confrontations are sometimes referred to
as "The Spanish Inquisition." As a rule, if a Python user starts using phrases
that have no relation to reality, they're probably borrowed from the Monty
Python series or movies. Some of these phrases might even pop up in this
book. You don't have to run out and rent The Meaning of Life or The Holy
Grail to do useful work in Python, of course, but it can't hurt.
While "Python" turned out to be a distinctive name, it's also had some
interesting side effects. For instance, when the Python newsgroup,
comp.lang.python, came online in 1994, its first few weeks of activity were
almost entirely taken up by people wanting to discuss topics from the TV
show. More recently, a special Python supplement in the Linux Journal
magazine featured photos of Guido garbed in an obligatory "nice red
Programming Python, 2nd Edition, O’Reilly
IT-SC book 35
uniform."
There's still an occasional post from fans of the show on Python's news list.
For instance, one poster innocently offered to swap Monty Python scripts
with other fans. Had he known the nature of the forum, he might have at
least mentioned whether they ran under DOS or Unix.
To help manage Python's growth, organizations aimed at supporting Python
developers have taken shape over the years: among them, 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. Although the future of the PSA is unclear as I write these words, it
has helped to support Python through the early years.
Today, Guido and a handful of other key Python developers, are employed by a
company named Digital Creations to do Python development on a full-time basis.
Digital Creations, based in Virginia, is also home to the Python-based Zope web
application toolkit (see http://www.zope.org). However, the Python language is
owned and managed by an independent body, and remains a true open source,
community-driven system.
Other companies have Python efforts underway as well. For instance, ActiveState
and PythonWare develop Python tools, O'Reilly (the publisher of this book) and a
company named Foretech both organize annual Python conferences, and O'Reilly
manages a supplemental Python web site (see the O'Reilly Network's Python
DevCenter at http://www.oreillynet.com/python). The O'Reilly Python Conference is
held as part of the annual Open Source Software Convention. Although the world of
professional organizations and companies changes more frequently than do
published books, it seems certain that the Python language will continue to meet the
needs of its user community.
1.3 The Compulsory Features List
One way to describe a language is by listing its features. Of course, this will be more
meaningful after you've seen Python in action; the best I can do now is speak in the
abstract. And it's really how Python's features work together, that make it what it is.
But looking at some of Python's attributes may help define it; Table 1-1 lists some of
the common reasons cited for Python's appeal.
Table 1-1. Python Language Features
Features Benefits
No compile or link steps Rapid development cycle turnaround
No type declarations Simpler, shorter, and more flexible programs
Programming Python, 2nd Edition, O’Reilly
IT-SC book 36
Automatic memory management Garbage collection avoids bookkeeping code
High-level datatypes and operations Fast development using built-in object types
Object-oriented programming Code reuse, C++, Java, and COM integration
Embedding and extending in C Optimization, customization, system "glue"
Classes, modules, exceptions Modular "programming-in-the-large" support
A simple, clear syntax and design Readability, maintainability, ease of learning
Dynamic loading of C modules Simplified extensions, smaller binary files
Dynamic reloading of Python
modules
Programs can be modified without stopping
Universal "first-class" object model Fewer restrictions and special-case rules
Runtime program construction Handles unforeseen needs, end-user coding
Interactive, dynamic nature Incremental development and testing
Access to interpreter information Metaprogramming, introspective objects
Wide interpreter portability Cross-platform programming without ports
Compilation to portable bytecode Execution speed, protecting source code
Standard portable GUI framework Tkinter scripts run on X, Windows, and Macs
Standard Internet protocol support Easy access to email, FTP, HTTP, CGI, etc.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 37
Standard portable system calls Platform-neutral system scripting
Built-in and third-party libraries
Vast collection of precoded software
components
True open source software May be freely embedded and shipped
To be fair, Python is really a conglomeration of features borrowed from other
languages. It includes elements taken from C, C++, Modula-3, ABC, Icon, and
others. For instance, Python's modules came from Modula, and its slicing operation
from Icon (as far as anyone can seem to remember, at least). And because of
Guido's background, Python borrows many of ABC's ideas, but adds practical
features of its own, such as support for C-coded extensions.
1.4 What's Python Good For?
Because Python is used in a wide variety of ways, it's almost impossible to give an
authoritative answer to this question. In general, any application that can benefit
from the inclusion of a language optimized for speed of development is a good target
Python application domain. Given the ever-shrinking schedules in software
development, this a very broad category.
A more specific answer is less easy to formulate. For instance, some use Python as
an embedded extension language, while others use it exclusively as a standalone
programming tool. And to some extent, this entire book will answer this very
question -- it explores some of Python's most common roles. For now, here's a
summary of some of the more common ways Python is being applied today:
System utilities
Portable command-line tools, testing systems
Internet scripting
CGI web sites, Java applets, XML, ASP, email tools
Graphical user interfaces
With APIs such as Tk, MFC, Gnome, KDE
Component integration
C/C++ library front-ends, product customization
Database access
Persistent object stores, SQL database system interfaces
Programming Python, 2nd Edition, O’Reilly
IT-SC book 38
Distributed programming
With client/server APIs like CORBA, COM
Rapid-prototyping /development
Throwaway or deliverable prototypes
Language-based modules
Replacing special-purpose parsers with Python
And more
Image processing, numeric programming, AI, etc.
"Buses Considered Harmful"
The PSA organization described earlier was originally formed in response to
an early thread on the Python newsgroup, which posed the semiserious
question: "What would happen if Guido was hit by a bus?"
These days, Guido van Rossum is still the ultimate arbiter of proposed
Python changes, but Python's user base helps support the language, work
on extensions, fix bugs, and so on. In fact, Python development is now a
completely open process -- anyone can inspect the latest source-code files
or submit patches by visiting a web site (see http://www.python.org for
details).
As an open source package, Python development is really in the hands of a
very large cast of developers working in concert around the world. Given
Python's popularity, bus attacks seem less threatening now than they once
did; of course, I can't speak for Guido.
On the other hand, Python is not really tied to any particular application area at all.
For example, Python's integration support makes it useful for almost any system that
can benefit from a frontend, programmable interface. In abstract terms, Python
provides services that span domains. It is:
A dynamic programming language, for situations in which a compile/link step is
either impossible (on-site customization), or inconvenient (prototyping, rapid
development, system utilities)
A powerful but simple programming language designed for development speed, for
situations in which the complexity of larger languages can be a liability (prototyping,
end-user coding)
A generalized language tool, for situations where we might otherwise need to invent
and implement yet another "little language" (programmable system interfaces,
configuration tools)
Programming Python, 2nd Edition, O’Reilly
IT-SC book 39
Given these general properties, Python can be applied to any area we're interested in
by extending it with domain libraries, embedding it in an application, or using it all
by itself. For instance, Python's role as a system tools language is due as much to its
built-in interfaces to operating system services as to the language itself. In fact,
because Python was built with integration in mind, it has naturally given rise to a
growing library of extensions and tools, available as off-the-shelf components to
Python developers. Table 1-2 names just a few; you can find more about most of
these components in this book or on Python's web site.
Table 1-2. A Few Popular Python Tools and Extensions
Domain Extensions
Systems programming Sockets, threads, signals, pipes, RPC calls, POSIX bindings
Graphical user interfaces Tk, PMW, MFC, X11, wxPython, KDE, Gnome
Database interfaces Oracle, Sybase, PostGres, mSQL, persistence, dbm
Microsoft Windows tools MFC, COM, ActiveX, ASP, ODBC, .NET
Internet tools JPython, CGI tools, HTML/XML parsers, email tools, Zope
Distributed objects DCOM, CORBA, ILU, Fnorb
Other popular tools SWIG, PIL, regular expressions, NumPy, cryptography
1.5 What's Python Not Good For?
To be fair again, some tasks are outside of Python's scope. Like all dynamic
languages, Python (as currently implemented) isn't as fast or efficient as static,
compiled languages like C. In many domains, the difference doesn't matter; for
programs that spend most of their time interacting with users or transferring data
over networks, Python is usually more than adequate to meet the performance
needs of the entire application. But efficiency is still a priority in some domains.
Because it is interpreted today,[3]
Python alone usually isn't the best tool for delivery
of performance-critical components. Instead, computationally intensive operations
can be implemented as compiled extensions to Python, and coded in a low-level
language like C. Python can't be used as the sole implementation language for such
components, but it works well as a frontend scripting interface to them.
Programming Python, 2nd Edition, O’Reilly
IT-SC book 40
[3]
Python is "interpreted" in the same way that Java is: Python source code is automatically
compiled (translated) to an intermediate form called "bytecode," which is then executed by
the Python virtual machine (that is, the Python runtime system). This makes Python scripts
more portable and faster than a pure interpreter that runs raw source code or trees. But it
also makes Python slower than true compilers that translate source code to binary machine
code for the local CPU. Keep in mind, though, that some of these details are specific to the
standard Python implementation; the JPython (a.k.a. "Jython") port compiles Python scripts to
Java bytecode, and the new C#/.NET port compiles Python scripts to binary .exe files. An
optimizing Python compiler might make most of the performance cautions in this chapter
invalid (we can hope).
For example, numerical programming and image processing support has been added
to Python by combining optimized extensions with a Python language interface. In
such a system, once the optimized extensions have been developed, most of the
programming occurs at the higher-level Python scripting level. The net result is a
numerical programming tool that's both efficient and easy to use.
Moreover, Python can still serve as a prototyping tool in such domains. Systems may
be implemented in Python first, and later moved in whole or piecemeal to a language
like C for delivery. C and Python have distinct strengths and roles; a hybrid
approach, using C for compute-intensive modules, and Python for prototyping and
frontend interfaces, can leverage the benefits of both.
In some sense, Python solves the efficiency/flexibility tradeoff by not solving it at all.
It provides a language optimized for ease of use, along with tools needed to
integrate with other languages. By combining components written in Python and
compiled languages like C and C++, developers may select an appropriate mix of
usability and performance for each particular application. While it's unlikely that it
will ever be as fast as C, Python's speed of development is at least as important as
C's speed of execution in most modern software projects.
On Truth in Advertising
In this book's conclusion we will return to some of the bigger ideas
introduced in this chapter, after we've had a chance to study Python in
action. I want to point out up front, though, that my background is in
Computer Science, not marketing. I plan to be brutally honest in this book,
both about Python's features and its downsides. Despite the fact that Python
is one of the most easy-to-use programming languages ever created, there
are indeed some pitfalls, which we will examine in this book.
Let's start now. Perhaps the biggest pitfall you should know about is this
one: Python makes it incredibly easy to throw together a bad design quickly.
It's a genuine problem. Because developing programs in Python is so simple
and fast compared to traditional languages, it's easy to get wrapped up in
the act of programming itself, and pay less attention to the problem you are
really trying to solve.
In fact, Python can be downright seductive -- so much so that you may need
to consciously resist the temptation to quickly implement a program in
Python that works, and is arguably "cool," but leaves you as far from a
maintainable implementation of your original conception as you were when
you started. The natural delays built in to compiled language development --
fixing compiler error messages, linking libraries, and the like -- aren't there
Exploring the Variety of Random
Documents with Different Content
Child labor laws of
today.
years were put to work for long hours under frightful conditions.
Underpaid and underfed, deprived of schooling, they grew up to be
physically and intellectually unfit and developed into inferior citizens.
[187]
Child labor was thought to be cheap, and from the employer’s
point of view it was; but in the long run society found it to be
incalculably expensive. Unrestricted child labor increased the
number of illiterates, promoted the spread of disease and crime,
augmented poverty, and bred discontent. The child is the father of
the man; and as our children are cared for so will the future
manhood and womanhood of the nation be. No fewer than two
million persons under fifteen years of age are engaged in some form
of wage-earning occupation in the United States today. Since they
are unable to protect themselves against overwork and
underpayment, the state must see to it that they are treated by their
employers with consideration and humanity.
The laws relating to child labor differ
considerably in the various states; in some the
provisions are much stricter than in others. In general the tendency
is to prohibit the regular employment of children under fourteen
years of age. Many of the states forbid the employment of persons
under sixteen years of age in night work or in certain dangerous
occupations, such as mining. The hours of labor for persons under
sixteen are also limited in some states to not exceeding eight per
day. Many other provisions restricting child labor are now in force,
and year by year new limitations are being added.[188]
In 1916
Congress undertook to place a general restriction on child labor
throughout the entire country by passing a law which forbade the
transportation and sale in interstate commerce of any goods made in
whole or in part by children under a designated age-limit. The
Supreme Court of the United States held this law to be
unconstitutional, however, declaring that the authority to regulate
commerce among the states does not empower Congress to control
the conditions of industry within the state boundaries. Congress has
since placed a ban upon child labor in another way, namely, by
providing that the profits of these industries which employ children
shall be taxed more heavily than the profits of those concerns which
do not.[189]
Some practical
difficulties.
The arguments for
minimum wage
laws.
Nature of these
laws.
Causes of
unemployment.
Minimum Wage Laws.—Investigations into
the subject made some years ago disclosed the
fact that not only were women and children
frequently overworked in industries but that they were often
underpaid as well. One reason for this underpayment was that many
of the women and children workers lived at home and did not need
to be entirely self-supporting. They merely contributed to the general
family earnings. They were thus in a position to work for smaller
wages than if they were entirely self-dependent. But there were also
many thousands of women and children who had to support
themselves entirely from their own earnings and to these the low rate
of wages meant hardship and suffering. It meant undernourishment,
physical break-down, and premature old age. It led to pauperism and
immorality. So the laws have once more intervened to protect the
well-being of the race against the fruits of industrial injustice by
providing that the wages of women and children in industry shall not
fall below a certain minimum.
Many of the states have put these minimum
wage laws upon their statute books. Sometimes
the minimum rate of wages is fixed in the law; more often it is
determined in the case of each industry by a state board after an
investigation. The minimum rate is set at such a point as will enable
the wage-earner to be self-supporting. Here, again, the basic
principle is that the actual cost of production, including the cost of
protecting society against things detrimental to it, should be paid by
the public which buys the goods. One practical
difficulty connected with the minimum wage plan
is that it tends to throw the less efficient employees out of work
altogether. The employer who is forced by law to pay a fixed
minimum in wages, no matter how unskillful the worker may be, will
promptly dismiss all those who do not give him, in work, the worth of
their wages. If a minimum wage is established in all industries,
where will the least skillful find employment?
The Problem of Unemployment.—The
greatest of all economic wastes today is that
which results from unemployment. The ideal condition would be to
have everybody employed all the time. If that could be accomplished
Some suggested
remedies.
How progress
toward a solution of
the problem is
being made.
we could produce a great deal more each year at lower cost.
Unemployment means that idle men must use what other workers
are producing. But it is not possible to do away with unemployment
altogether. Some trades are seasonal in character, that is to say,
busy at one period of the year and slack during others. In northern
regions the building trades, bricklaying, outdoor carpentry, and so
on, are in this category. The larger part of the unemployment,
however, is due to other than seasonal causes. It is due rather to
trade depressions which from time to time cause the shutting down
of industrial establishments and it is caused in some degree by the
lack of careful planning on the part of the employer. The number of
unemployed workers throughout the country varies greatly from time
to time. It may be as low as five per cent or as high as forty per cent
of the entire number.
Various plans for lessening the evils of
unemployment have been suggested, but they
all present some practical difficulties. Better vocational training would
reduce the number of unskilled workers; and it is the unskilled who
contribute most largely to the ranks of the unemployed. The
establishment of public employment offices has done something to
bring workers into touch with available jobs. It is proposed that we
have a more careful planning of state and municipal improvements
so that the heaviest demand for labor on public works would come at
times when unemployment is most prevalent—this, it is urged, would
help alleviate the trouble even though it might not go very far in
solving the whole problem. Much would be accomplished by the
better organization of industrial production and by some scheme of
co-operation among employers which would enable workers to be
transferred from one industry to another. Great practical obstacles
are in the way of doing this on a large scale.
Some large concerns have already adopted
the plan of setting aside each week a certain
percentage of the total pay roll as an
unemployment reserve. Then, whenever
workers are temporarily out of employment through the slackening of
business and not through any fault of their own, a certain weekly
wage is paid to them from this reserve. Something will also be
The experience of
Great Britain and
Germany.
Unemployment
insurance.
accomplished in the way of reducing unemployment by better
vocational guidance, for young men and women often go into
employments which afford no chance of promotion and which they
subsequently find to be unsuited to their tastes. Many large
industries now bestow great care upon the selection of new
employees. All applicants are dealt with through a special official
known as the employment manager, whose function it is to make
reasonably sure that the applicant is fitted for the position. Foremen
and bosses are not allowed to discharge employees at will. The
complaints must first be referred for investigation to the employment
manager’s office. This plan will also help alleviate unemployment if it
becomes general.
Unemployment insurance has been tried in a
few European countries and has been
advocated in America. This plan contemplates that each employer
shall contribute to a fund from which a stated wage scale shall be
paid to those who remain out of work through no fault of their own, or
that the government shall provide such a fund from the proceeds of
taxes. It is easy to see that a scheme of this sort might be seriously
abused, yet so long as the problem of unemployment remains
serious we must strive to find some way of solving it.
Old-Age Pensions.—Most wage-earners do not save enough to
provide for themselves in old age. The result is that after long years
of toil they are dependent upon their children, or must eke out a
precarious existence by doing odd jobs, or must be supported by the
public poor-relief funds. This is not a desirable
state of affairs and in some European countries,
notably in Great Britain and in Germany,
systems of old-age pensions for workers have been established. In
Germany the worker pays a small amount each week into the fund;
the employer pays an equal amount and the government pays the
rest. In Great Britain the employers and the government pay it all.
Every wage-earner, on reaching old age, receives a small weekly
allowance for the rest of his days.[190]
The cost of an old-age pension
system is enormous, but in the long run it is likely to represent real
economy. Sooner or later the system will probably be established in
this country; the only question is whether, when it comes, the wage-
The patriotism of
American labor.
earner should be required to pay a regular contribution during the
years in which he is able to do full work.
American Labor and the War.—Among the
various factors which helped to win the World
War the loyalty and enthusiasm of American labor should be
accorded a high place. War always creates a great shortage of
workers, partly because so many able-bodied men are taken into the
army and partly because of the tremendous need for workers in
munition plants and other war industries. During war, therefore, the
labor organizations are always in a position to make demands which
cannot well be refused. It is quite true that American labor took
advantage of its opportunities during the World War; but so did the
employers. The wages of labor rose everywhere, as did the profits of
industry. Nevertheless it can fairly be said that labor co-operated with
the government at all the essential points and produced the
uninterrupted flow of materials which was needed to ensure victory.
Certain it is that without this co-operation on the part of labor the
United States could not have figured so prominently in deciding the
ultimate issue of the great conflict.
General References
Isaac Lippincott, Economic Development of the United States, pp. 491-511;
R. T. Ely, The Labor Movement in America, pp. 34-91 (Growth and Present
Conditions of Labor Organizations);
T. S. Adams and H. L. Sumner, Labor Problems, pp. 461-501 (Labor Laws);
F. T. Carlton, Organized Labor in American History, pp. 11-44 (Epochs in the
History of Organized Labor); pp. 169-197 (Labor Parties); pp. 198-225 (Ideals of
the Wage Earner);
R. F. Hoxie, Trade Unionism in the United States, pp. 254-275 (Collective
Bargaining);
John R. Commons and J. B. Andrews, Principles of American Labor
Legislation, pp. 35-90 (Individual Bargaining);
Samuel Gompers, American Labor and the War, passim.
Group Problems
1. The origin, growth, and aims of labor organizations. The organization of
industry before the Industrial Revolution. Rise of the factory system. Creation of a
labor class. Early conditions of factory employment. Beginnings of labor
organizations. Early attitude of the law and the courts. Growth of labor
organizations during the past half century. Central organizations and national
bodies. Present-day aims of labor organizations—economic, social, and political.
Specific features of organized labor’s program. Labor as a factor in politics. The
movements for industrial democracy. References: T.S. Adams and H.L. Sumner,
Labor Problems, pp. 214-279; Sidney Webb, History of Trade Unionism, pp. 1-56;
431-541; Mary Beard, Short History of the American Labor Movement, pp. 47-79;
F. T. Carlton, Organized Labor in American History, pp. 11-44; 198-225; R. F.
Hoxie, History of Trade Unionism in the United States, pp. 211-252 (The Law in
Relation to Labor); John R. Commons (editor), History of Labor in the United
States, passim; R. T. Ely, The Labor Movement in America, pp. 34-91; P. F.
Brissenden, History of the I. W. W., pp. 83-112 (The I. W. W. vs. the A. F. of L.).
2. The American Federation of Labor: its history, aims, and achievements.
References: Samuel Gompers, American Labor and the War, pp. 186-196; John
Mitchell, Organized Labor, pp. 397-406; F. T. Carlton, History and Problems of
Organized Labor, pp. 75-82; Mary R. Beard, Short History of the American Labor
Movement, pp. 86-149; G. G. Groat, Organized Labor in America, pp. 82-99;
Helen Marot, American Labor Unions, pp. 11-28.
3. The arbitration of industrial disputes. References: T. S. Adams and Helen
Sumner, Labor Problems, pp. 295-332; Sidney Webb, Industrial Democracy, pp.
222-246; N. P. Gilman, Methods of Industrial Peace, pp. 301-345; R. T. Ely, The
Evolution of Industrial Society, pp. 374-397; John Mitchell, Organized Labor, pp.
337-346; F. W. Taussig, Principles of Economics, Vol. II, pp. 303-322.
4. The general principles of labor legislation. References: W. S. Jevons,
The State in Relation to Labor, pp. 1-32; F. W. Taussig, Principles of Economics,
Vol. II, pp. 285-302; John R. Commons and J. B. Andrews, Principles of Labor
Legislation, pp. 1-34; H. S. Person, Labor Laws and Their Enforcement, passim.
Short Studies
1. The four epochs in the history of organized labor. F. T. Carlton,
Organized Labor in American History, pp. 11-44.
2. Labor and politics. F. T. Carlton, History and Problems of Organized Labor,
pp. 169-197.
3. The Knights of Labor: why they failed. Mary R. Beard, Short History of
the American Labor Movement, pp. 116-126.
4. The right to strike. John Mitchell, Organized Labor, pp. 299-323.
5. Collective bargaining. Final Report of the U. S. Industrial Commission, pp.
843-847.
6. The use of injunctions in labor disputes. G. L. Bolen, Getting a Living, pp.
548-580; J. R. Commons, Trade Unionism and Labor Problems, pp. 156-163.
7. The Kansas plan. H. J. Allen, The Party of the Third Part, pp. 16-91.
8. Workmen’s compensation. John R. Commons and J. B. Andrews,
Principles of American Labor Legislation, pp. 356-385. See also the publications
on this subject issued by the National Industrial Conference Board.
9. Women and children in industry. T. S. Adams and H. L. Sumner, Labor
Problems, pp. 19-67.
10. The problem of unemployment. E. T. Towne, Social Problems, pp. 140-
159; W. H. Beveridge, Unemployment, 3d ed., pp. 1-15 (Great Britain).
11. Profit sharing as a solution of industrial problems. T. S. Adams and H. L.
Sumner, Labor Problems, pp. 333-378.
12. Old age pensions. W. H. Dawson, Social Insurance, pp. 128-165; F. W.
Lewis, State Insurance, pp. 148-170.
Questions
1. Explain why labor organizations came into existence during the nineteenth
century. On the whole have they been a benefit to industry or not? Give your
reasons.
2. Give some reasons for expecting trade unions to be stronger in certain
employments than in others. In which of the following employments would you
expect the unions to be strong, and in which would you expect them to be weak:
(a) railroading; (b) domestic service; (c) school teaching; (d) farming; (e) mining; (f)
steel-making? Give reasons for your expectations in each case.
3. With what points in the program of the American Federation of Labor do you
agree and with what ones do you disagree?
4. The closed shop is sometimes criticised as being “un-American” and the open
shop has been called the “American plan”. What does this mean?
5. Are there any employments, public or private, in which strikes should not be
permitted?
6. Why should the consumer pay the costs of all industrial accidents? Explain
how he does so where workmen’s compensation acts have been passed.
7. In your opinion would the legislature be justified in limiting to eight hours per
day the labor of (a) women in candy factories; (b) men who work on farms; (c) men
who work in coal mines; (d) physicians; (e) waitresses in hotels; (f) female
servants; (g) members of the fire-protection service in cities; (h) motormen on
street cars? Give your reasons in each case.
8. Give your views as to the minimum age at which any person should be
permitted to engage in regular employment for wages. At what age should
employment in night work be permitted? Should persons under fourteen years of
age be allowed to work for wages after school hours, on Saturdays, and during
vacations?
9. A girl of sixteen has graduated from grammar school and could obtain a
position as clerk in a millinery store at eight dollars a week. She is living at home
and does not have to support herself. But the minimum wage for clerks in stores
happens to be ten dollars per week and the owner will not pay so much. Is there
any injustice here?
10. How can the evil of unemployment be reduced? What abuses might arise in
connection with unemployment insurance? Who pays the cost of unemployment
now? Argue whether we should or should not place industrial unemployment on
the same basis as industrial accidents.
Topics for Debate
1. The demand for collective bargaining is (or is not) justified.
2. A plan of old-age pensions, like that now maintained in Great Britain, should
be established in the United States.
Money supplants
barter.
CHAPTER XXII
CURRENCY, BANKING, AND CREDIT
The purpose of this chapter is to explain what money is, what purposes it
serves, how banks conduct their business, and how credit facilitates trade.
The Origin of Money.—The use of money is
one of the marks of civilization. In primitive
communities money was unknown. Buying and selling was by barter,
the exchange of one commodity for another. The man with too much
corn exchanged corn for cattle or for a boat or for skins with which to
clothe himself. But exchange by barter is a slow and clumsy method
because it means that two persons must be found each of whom
wants exactly what the other has to sell, a thing which does not
easily happen. With the growth of trade, accordingly, it became
necessary to find a medium of exchange, in other words some single
commodity which is so readily exchangeable for all other
commodities that it can be used to facilitate buying and selling.
Some of the Indians of North America used the ends of shells, or
wampum, for this purpose. The early colonists in Virginia chose
tobacco as a temporary medium of exchange, it being in universal
demand. People accepted tobacco in exchange for things which they
wished to sell, and gave tobacco for things which they desired to
buy. This was not because they wanted tobacco for their own use
but because of all commodities in the colony tobacco was the most
easy to exchange for other things at a moment’s notice. No ordinary
form of merchandise, however, makes an entirely satisfactory
medium of exchange and all of them in time gave way to the
precious metals, gold and silver, which are now everywhere used for
this purpose.[191]
1. Value.
2. Stability.
3. Convenience.
Money as a
standard of value
and a measure of
deferred payments.
The qualities which
money must have:
The Functions which Money Serves.—
Money, however, serves not only as a medium of
exchange but as a standard of value and a
measure for future payments. Money is the
common denominator by means of which we express the value of
different commodities. If money were not in existence, how could we
state the value of anything? It would be of little avail to say that a suit
of clothes is worth ten hats, for this would merely beg the question:
How much is a hat worth? Money performs the function of providing
a uniform scale into which all values can be translated. When we
say, therefore, that a suit of clothes is worth forty dollars and that
hats are worth four dollars apiece we are measuring both
commodities according to the same standard of value. Money also
facilitates the use of credit by providing a measure for deferred
payments. People cannot well agree to indefinite future obligations;
they must know exactly what a debt amounts to. The use of money
enables men to borrow today with the understanding that they will
repay the same amount at some future date.
Characteristics of Money.—Gold and silver
are best adapted to facilitate exchange because
they possess, in high degree, certain qualities which money must
have in order to fulfil its functions properly. What are these qualities?
To serve acceptably as money a substance must
have, in the first place, some value in itself; it
must therefore have utility as a basis of value. A worthless
substance, which nobody wants, would not do.
Second, it must not only have value but stability
of value. To serve efficiently as money a metal must not be subject to
wide and frequent fluctuations in what it is worth. A substance which
might be worth much today and little tomorrow would not be
satisfactory. Gold and silver, being produced in limited quantities, are
more nearly stable in value than any other metals, gold being
particularly so. Third, the metal used as money
must possess relatively high value in proportion
to its bulk so that it can be easily passed from hand to hand. There
was a tradition in ancient Greece that Lycurgus compelled the
Lacedaemonians to use iron money in order that its weight might
4. Durability.
5. Uniformity.
6. Divisibility.
7. Cognizability.
Gold is the
American standard
of values.
deter them from overmuch trading. If iron were used as currency
today a dime would weigh more than a pound.[192]
In a word the
metal used as money must be portable, easy to carry around.
Fourth, it must be relatively indestructible, not
subject to rapid decay or rusting. Gold and silver
satisfy this requirement, for time does not destroy their value nor do
they suffer much wear and tear through handling. It is believed that
some of the gold which is in the coinage of European countries today
served as money in the time of the Romans.
Fifth, it must be homogeneous, that is, it must
not vary in quality, otherwise equal amounts of it would not have the
same value. In order that we may reckon things in terms of money
the units must be equal and similar so that twice one will always
make two. If we were to use diamonds as money, it would not always
happen that two stones would be worth exactly twice as much as
one. Sixth, it must be easily divisible without loss
of value, for we need small units of money as
well as large ones. One great difficulty which primitive people found
in using the skins of animals as money was that they could not be
cut into portions without destroying their value altogether. Nobody
would take, for example, a quarter of a skin in payment for a
basketful of corn. But gold and silver can be divided at will and yet
retain an exactly proportionate value. Finally, it
must be a metal or other substance the
genuineness of which can be easily determined. If every person who
receives money had to scrutinize, weigh, and test it, the processes of
trade would be intolerably delayed.[193]
Gold and silver may not
themselves be readily cognizable by the uninitiated, but they are
easy to stamp into coins with a stamp or design and this impression
cannot be easily counterfeited. The various countries of the world
adopted gold and silver as their chief media of exchange because
these metals fulfil in the largest degree the foregoing requirements.
For small units of currency nickel and bronze are utilized because
subsidiary coins of gold and silver would be too small.
The Coinage of the United States.—In the
United States gold is the standard of values.
This does not mean that gold is circulated from
The United States
mints.
In 1792.
In 1834.
In 1873.
The ratio between
gold and silver.
hand to hand in every transaction, but merely that all economic
values are expressed in terms of gold coin. The actual payments
may be made in paper notes, or in silver, nickel, or copper coins. The
monetary system of the United States is based upon the decimal
system, which was adopted in 1784 at the suggestion of Thomas
Jefferson. This means that we reckon in fractions and multiples of
ten—ten cents one dime, ten dimes one dollar, and ten dollars one
eagle. For convenience there are also additional coins, such as
nickels, quarter dollars, half dollars, and half-eagles. No gold dollars
are now coined, as they were found to be too small for convenience.
[194]
The mint has also ceased coining quarter eagles but continues to
make five, ten, and twenty dollar gold pieces although these coins
remain for the most part in the banks where they are held as
reserves. Very little gold coin is in circulation anywhere in the world
today. The coining of money is wholly within the jurisdiction of the
national government; no state is allowed to make or issue coins. The
making of coins takes place at four mints, which
are located at Philadelphia, New Orleans,
Denver, and San Francisco.[195]
If you look at the reverse side of a
recently minted coin, you will find, near the base, a small letter
indicating the mint at which the coin was struck; if there is no such
letter, the coin was minted at Philadelphia.
The Controversy over Bimetallism.—In
1792, when the first American mint was
established, Congress provided by law that there should be two
monetary units, the gold dollar and the silver dollar—the ratio
between the two, in terms of weight, being fixed at fifteen to one. Any
person bringing gold or silver bullion to the mint was entitled to have
it made into coins at this ratio, which corresponded to the relative
market value of the two metals in 1792. Silver
eventually cheapened in relation to gold,
however, and in time only silver bullion came to be coined. So
Congress in 1834 reduced the weight of the gold
dollar and made the ratio sixteen to one. This, in
turn, proved to be an under-valuation of silver, and no silver now
came to the mint to be coined.[196]
In 1873, after
silver dollars had practically dropped out of
In 1893.
Final settlement of
the question in
1900.
Our early
experience with
circulation Congress abolished the free coinage of silver altogether.
[197]
Presently, however, there was a popular demand for a
resumption of silver coinage and the minting of silver dollars was
recommenced,[198]
but only on a limited scale;
and in 1893 it was once more abandoned.[199]
This action on the part of Congress raised a great hue and cry in
certain sections of the country, especially in the South and West.
Free coinage of silver was desired not only by owners of mines who
had silver to sell but by large numbers of farmers who believed that
gold was becoming too scarce to serve as the sole standard of
value. Scarcity of gold meant scarcity of money, and scarcity of
money meant low prices for wheat. If money were plentiful, prices
would go higher, and the way to get more money was to coin into
dollars all the silver that would come to the mint. That was the
farmers’ argument.
The “Cross of Gold” Campaign.—The leaders of the Democratic
party took advantage of this widespread agricultural grievance. At
the national convention of that party, held at Chicago in the summer
of 1896, Mr. W. J. Bryan swept the delegates off their feet with his
denunciation of the “few financial magnates who corner the money of
the world” and his plea for the poor man’s dollar. “You shall not press
upon the brow of labor this crown of thorns”, he declaimed. “You
shall not crucify mankind upon a cross of gold.” The delegates, amid
tumultuous cheering and enthusiasm, thereupon nominated the
young orator from Nebraska as their candidate for President and
made the free coinage of silver at a ratio of “sixteen to one” a
fundamental part of the Democratic platform in the election
campaign. But Bryan was overwhelmingly defeated and the clamor
for free silver soon subsided. In 1900 Congress
passed the Currency Act, which declared gold to
be the sole standard and directed the secretary
of the treasury to maintain all other forms of currency at a parity with
gold. This means that every silver dollar, whether the silver which it
contains be worth a dollar or not, is guaranteed by the national
government to be worth a gold dollar.
Paper Money.—Our experience with paper
money goes back to colonial days when bills of
paper currency.
What the
constitution
provides as regards
paper money.
The seven kinds of
paper money in
use.
credit were issued by Massachusetts to pay the
costs of the expedition against Quebec in 1690. But no great
amounts were issued until the Revolutionary War; then the various
state governments as well as the Continental Congress printed and
issued notes to the par value of nearly half a billion dollars. In the
earlier years of the war this paper currency circulated at its face
value although there was no gold or silver reserve behind it; but as
the struggle dragged on and notes by the million kept being issued
they began to depreciate until eventually this continental paper
currency was worth only a fraction of a cent per dollar. Hence the
origin of the slang expression “not worth a continental”. The notes for
the most part were never redeemed; they merely became worthless
and passed out of circulation.
Naturally this experience made the people
averse to paper money and when the
constitution of the United States was framed it
contained a provision that “no state shall emit
bills of credit (or) make anything but gold and silver coin a tender in
payment of debts”. It was strongly urged that the national
government should also be prohibited from issuing paper money, but
in the end it was decided not to make any express prohibition, so the
constitution is silent as regards the authority of the national
government to emit bills of credit. It neither gives this power nor
denies it. In due course, however, Congress authorized the issue of
legal-tender notes or greenbacks, and the Supreme Court upheld its
right to do this on the ground that the constitution expressly gives
Congress the power to borrow money and that the issue of paper
money is a reasonable method of borrowing. But although the
national government has itself the legal right to issue paper money,
either with or without a reserve behind it, most of the paper money
now in circulation is issued by the federal reserve board or by the
federal reserve banks under authority granted by Congress.
Paper Notes now in Circulation.—There are
several kinds of paper notes now in circulation.
[200]
These include silver certificates, gold
certificates, treasury notes, and greenbacks issued directly by the
national government, national bank notes, federal reserve notes, and
Inconvertible paper
money.
Paper money has
some advantages in
convenience and
cheapness.
Why not abolish
money?
federal reserve bank notes. The provisions for the redemption of
these different types of paper money vary greatly, and each is
protected by a different reserve, but in actual fact the holder of any
unit of paper money can obtain gold for it if he so desires. This is
true even of the silver certificates which, strictly speaking, are
redeemable only in silver dollars. The arrangements under which the
national banks, the federal reserve banks, and the federal reserve
board are permitted to issue paper money will be discussed
presently.
Why do we have paper money? Chiefly
because it is, in many respects, more
convenient for use than metallic money. In large
amounts it is not so bulky as silver or gold would
be. There is also the advantage that when paper money wears out it
can be cheaply replaced. If gold coins were continually in circulation
from hand to hand, they would gradually wear down and the
monetary loss would be considerable. Hence it is better to keep the
gold in the bank vaults and circulate the paper, which represents
gold, in its stead. But a sound system of paper money should always
provide for the redemption of the notes, which means that the notes
should have an adequate reserve behind them. This reserve should
be in gold or in the equivalent of gold.
Unredeemable paper money, issued without an
adequate reserve behind it, leads practically always to depreciation
and thereby to heavy losses on the part of the people who have
taken the money in good faith. That was what happened in the case
of the assignats of the French Revolution, the continental currency in
the American Revolution, and the paper money of several European
countries during the World War.[201]
It is folly to try to finance a war or
any other national enterprise by issuing fiat currency, as it is called,
which is paper currency with only the word of the government and no
substantial reserve behind it. Better tax the people outright than
make them take money as legal tender which is not worth what it
purports to be.[202]
Radicals sometimes say: “Let us do away with
money altogether”. Instead of money, they say,
we might use “labor checks”, each check representing a given
amount of labor. One hour of labor, let us say, would then be the
standard of value instead of 23.2 grains of gold. This arrangement,
however, would not abolish money, but only change the nature of the
basis upon which the value of money is calculated. The labor checks
would be money in every sense of the word. There is only one way
to abolish money and that is to go back to barter.
1. As institutions of
deposit.]
2. As agencies for
loaning money.
3. Sometimes also
as issuers of paper
money.
4. To transfer funds
from one place to
another.
Banks serve:
The Banking System
What Functions do Banks Perform?—
Banks are established and maintained to satisfy
certain needs which arise wherever men carry on extensive trade
with one another. In the first place when money
is accumulated by people in the course of their
business some safe place is needed to keep it. Banks, therefore,
serve as institutions of deposit. In the second
place, as business develops, it becomes
necessary for people to borrow money. Banks facilitate this
borrowing. Their two primary functions are to receive deposits and to
make loans. But in order that they may perform these two primary
functions to the best advantage the banks have assumed other
subsidiary functions as well. Frequently they
issue bank notes, or the bank’s own promises to
pay, for use in general circulation. They sell
drafts or bills of exchange, thus enabling people
to transfer funds from one city or country to
another without the trouble and risk of sending
the actual money. As a rule they provide safe-deposit vaults in which
customers, on payment of a small sum, are permitted to keep their
valuables. These vaults are fire-proof and burglar-proof. Banks also
collect money which may be due to a customer from someone
elsewhere. They help the national and state governments to sell their
bonds. Frequently they act as trustees, holding property for children
until they grow up or for other persons who are unable to look after
the property for themselves. Without banks it would be difficult, if not
impossible, to carry on the operations of modern business.
The Early American Banking System.—The national constitution
contains no mention of banks or banking. Hence it was assumed that
the power to charter banks would rest with the states. The states
assumed this authority but the national government desired to
exercise it also, and during the first thirty years of its existence
established two great banks, both of which became unpopular and
ultimately went out of existence. The first Bank of the United States,
established in 1791, ceased to do business in 1811; the second
Their functions.
Their reserves.
Present
organization of the
national banks.
bank, chartered in 1816, incurred the wrath of President Andrew
Jackson and went to the wall in 1836.[203]
From this date to the Civil
War the state banks, of which a large number were established in all
parts of the country, had the field to themselves.
The National Banking Act of 1863.—During the Civil War,
however, the national government encountered great difficulty in
raising funds. When it issued bonds the people would not buy them
readily. The state banks showed very little interest in marketing
them. So Congress, in this emergency, decided to establish a
system of national banks in order to facilitate the sale of war bonds.
The National Banking Act, passed in that year, laid a heavy tax upon
the paper money of all state banks, with intent to drive this currency
out of circulation. It then provided that any bank chartered by the
national government might issue untaxed paper money provided it
bought United States bonds to a designated amount and deposited
these bonds in Washington as security. In other words the Act of
1863 aimed to provide a uniform system of bank notes throughout
the country, these notes to be backed by government bonds. The
plan worked well and its main provisions have been retained to this
day.
National banks are owned by private
individuals who subscribe the capital stock.
These stockholders, or shareholders, elect the
bank’s officers, who in turn manage the business. The profits go to
the shareholders in the form of annual dividends. Each national bank
must buy a designated amount of United States bonds and these
bonds are deposited in Washington. In return the bank receives an
equal amount of paper notes, with its own name engraved thereon,
and these notes the bank pays out over its counters, thus putting
them in general circulation. If the bank should become insolvent, the
government would redeem the notes since it holds the bonds as
security. The national banks receive money on
deposit, make loans, and perform the various
other banking functions. They are strictly regulated by national law;
they must make periodic reports and are frequently inspected by
officials from Washington. One requirement is
that they shall always maintain a certain
State banks and
trust companies.
Defects of the
national banking
system due to the
concentration of
reserves and lack of
flexibility.
How the Federal
Reserve system
remedies these
defects.
“reserve” so that they may be in a position to make all payments
which may be called for by their customers. The supervision of the
national banks is in the hands of an official known as the Comptroller
of the Currency, who is appointed by the President.
In addition to the national banks there are
state banks and trust companies throughout the
country operating under state charters. These institutions do not
issue paper money but perform all the other banking functions.[204]
Their business is regulated by the laws of the state in which they are
located and they are supervised by state officials. The laws relating
to state banks and trust companies differ considerably from state to
state.
The Federal Reserve Banks.—Although the
national banking system worked pretty well for
fifty years after its establishment, certain defects
came to be recognized. One of these defects, in
actual practice, was the necessity of always
keeping available a “reserve” amounting to a
certain percentage of each bank’s total deposits. It was not
necessary to keep this reserve in the bank’s own vaults; a part of it
might be placed upon deposit in larger banks where it would draw
interest. As matters turned out, a considerable portion of the
reserves was usually deposited with large banks in New York City. In
times when business was good and money plentiful, this
arrangement worked very well, but when periods of business
depression arrived and money became scarce every small bank
naturally drew upon its reserve deposits in the larger banks, which
found difficulty in paying them all at the same time. Moreover, it was
found from experience that during times of business prosperity the
country needed a large increase in paper money while the national
banking system, as established in 1863, proved too rigid to meet the
business needs of the country.
In 1913, accordingly, Congress made
provision for the establishment of a Federal
Reserve system which does not displace but
supplements the operations of the national
banks. By an act passed in that year provision was made for the
The Federal
Reserve Board.
How they give
flexibility to the
whole banking
system of the
country.
Functions of the
Federal Reserve
Banks.
establishment of twelve federal reserve districts, with a federal
reserve bank in each. The capital stock of each federal reserve bank
is contributed by national or state banks within the districts, these
contributors being then known as “member banks”. The national
government also subscribes a part of the capital stock when
necessary. Each federal reserve bank is
controlled by officials, some of whom are elected
by the member banks and some appointed by the national
government through a body known as the Federal Reserve Board.
This board is composed of the Secretary of the Treasury, the
Comptroller of the Currency, and five other members appointed by
the President.
These federal reserve institutions are bankers’
banks. They do business with banks only, not
with individuals. They receive deposits from
banks and lend money to banks. The member banks now keep with
them a portion of their reserves. In this way the reserves are
mobilized at twelve different financial centers where they can be
readily drawn upon.[205]
The Federal Reserve Board has authority to
increase or decrease the percentage of reserves which the member
banks are required to maintain, thus giving the reserve system a
large degree of flexibility. Whenever a member bank needs
additional paper money for circulation it goes to the federal reserve
bank of its district and deposits any sound “collateral”, that is to say,
any acceptable security, and receives federal reserve notes of like
value in return. This collateral may be in the form of government
bonds or it may be, and more often is, “commercial paper”. By
commercial paper is meant the notes or other
obligations of corporations and individuals which
have been given to the member banks in return
for loans made to such corporations and
individuals. The federal reserve banks are
authorized to issue federal reserve notes, to an unlimited extent on
the security of this collateral provided they also keep a gold reserve
amounting to forty per cent of the total notes issued. In addition they
are empowered to issue federal reserve bank notes secured by
United States bonds in the same way as national bank notes are
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookfinal.com
Ad

More Related Content

Similar to Get Programming Python with CD 2nd Edition Mark Lutz free all chapters (20)

Python Distilled Developer s Library 1st Edition David Beazley
Python Distilled Developer s Library 1st Edition  David BeazleyPython Distilled Developer s Library 1st Edition  David Beazley
Python Distilled Developer s Library 1st Edition David Beazley
gemsergrzona
 
Python Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + JenkinsPython Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + Jenkins
Fagun Priyadarshi
 
Why Python Should Be Your First Programming Language
Why Python Should Be Your First Programming LanguageWhy Python Should Be Your First Programming Language
Why Python Should Be Your First Programming Language
Edureka!
 
The Onward Journey: Porting Twisted to Python 3
The Onward Journey: Porting Twisted to Python 3The Onward Journey: Porting Twisted to Python 3
The Onward Journey: Porting Twisted to Python 3
Craig Rodrigues
 
Exploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python LibrariesExploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python Libraries
MinhazulAbedin27
 
Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...
coughhouey74
 
Python
Python Python
Python
Edureka!
 
Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...
grocegowerah
 
Professional Git 1st Edition Brent Laster
Professional Git 1st Edition Brent LasterProfessional Git 1st Edition Brent Laster
Professional Git 1st Edition Brent Laster
thomesaresia
 
Cython compiler
Cython compilerCython compiler
Cython compiler
Tanikella Sai Abhijyan
 
C 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. DeitelC 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. Deitel
bredsmomad
 
Consumer centric api design v0.4.0
Consumer centric api design v0.4.0Consumer centric api design v0.4.0
Consumer centric api design v0.4.0
mustafa sarac
 
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Internet World Wide Web How to Program 2nd Edition Harvey M. DeitelInternet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
rattaaseifu
 
Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023
Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023
Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023
Peter Gallagher
 
Python programming-2-2048 (30 files merged).ppt
Python programming-2-2048 (30 files merged).pptPython programming-2-2048 (30 files merged).ppt
Python programming-2-2048 (30 files merged).ppt
pprince22982
 
Python programming notes all in one python ppt
Python programming notes all in one python pptPython programming notes all in one python ppt
Python programming notes all in one python ppt
pprince22982
 
Python in the browser
Python in the browserPython in the browser
Python in the browser
PyCon Italia
 
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
raaenvalko0u
 
Prerequisite for Artificial Intelligence.pptx
Prerequisite for Artificial Intelligence.pptxPrerequisite for Artificial Intelligence.pptx
Prerequisite for Artificial Intelligence.pptx
krishan8018
 
AI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptx
AI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptxAI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptx
AI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptx
Neelkaranbind
 
Python Distilled Developer s Library 1st Edition David Beazley
Python Distilled Developer s Library 1st Edition  David BeazleyPython Distilled Developer s Library 1st Edition  David Beazley
Python Distilled Developer s Library 1st Edition David Beazley
gemsergrzona
 
Python Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + JenkinsPython Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + Jenkins
Fagun Priyadarshi
 
Why Python Should Be Your First Programming Language
Why Python Should Be Your First Programming LanguageWhy Python Should Be Your First Programming Language
Why Python Should Be Your First Programming Language
Edureka!
 
The Onward Journey: Porting Twisted to Python 3
The Onward Journey: Porting Twisted to Python 3The Onward Journey: Porting Twisted to Python 3
The Onward Journey: Porting Twisted to Python 3
Craig Rodrigues
 
Exploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python LibrariesExploring Five Lesser-Known Python Libraries
Exploring Five Lesser-Known Python Libraries
MinhazulAbedin27
 
Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...
coughhouey74
 
Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...Using MPI third edition Portable Parallel Programming with the Message Passin...
Using MPI third edition Portable Parallel Programming with the Message Passin...
grocegowerah
 
Professional Git 1st Edition Brent Laster
Professional Git 1st Edition Brent LasterProfessional Git 1st Edition Brent Laster
Professional Git 1st Edition Brent Laster
thomesaresia
 
C 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. DeitelC 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. Deitel
bredsmomad
 
Consumer centric api design v0.4.0
Consumer centric api design v0.4.0Consumer centric api design v0.4.0
Consumer centric api design v0.4.0
mustafa sarac
 
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Internet World Wide Web How to Program 2nd Edition Harvey M. DeitelInternet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
rattaaseifu
 
Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023
Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023
Building a Raspberry Pi Robot with Dot NET 7, Blazor and SignalR - TechDays 2023
Peter Gallagher
 
Python programming-2-2048 (30 files merged).ppt
Python programming-2-2048 (30 files merged).pptPython programming-2-2048 (30 files merged).ppt
Python programming-2-2048 (30 files merged).ppt
pprince22982
 
Python programming notes all in one python ppt
Python programming notes all in one python pptPython programming notes all in one python ppt
Python programming notes all in one python ppt
pprince22982
 
Python in the browser
Python in the browserPython in the browser
Python in the browser
PyCon Italia
 
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
raaenvalko0u
 
Prerequisite for Artificial Intelligence.pptx
Prerequisite for Artificial Intelligence.pptxPrerequisite for Artificial Intelligence.pptx
Prerequisite for Artificial Intelligence.pptx
krishan8018
 
AI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptx
AI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptxAI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptx
AI_Day2_l it is to be of this ai ppt for anyone to be to out of thislearn.pptx
Neelkaranbind
 

Recently uploaded (20)

Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
How to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 SalesHow to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 Sales
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Dastur_ul_Amal under Jahangir Key Features.pptx
Dastur_ul_Amal under Jahangir Key Features.pptxDastur_ul_Amal under Jahangir Key Features.pptx
Dastur_ul_Amal under Jahangir Key Features.pptx
omorfaruqkazi
 
How to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale OrderHow to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale Order
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdfGENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
Quiz Club of PSG College of Arts & Science
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18
Celine George
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERSIMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
rajaselviazhagiri1
 
MICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdfMICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdf
DHARMENDRA SAHU
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-17-2025 .pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-17-2025  .pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-17-2025  .pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-17-2025 .pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
How to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 SalesHow to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 Sales
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Dastur_ul_Amal under Jahangir Key Features.pptx
Dastur_ul_Amal under Jahangir Key Features.pptxDastur_ul_Amal under Jahangir Key Features.pptx
Dastur_ul_Amal under Jahangir Key Features.pptx
omorfaruqkazi
 
How to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale OrderHow to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale Order
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18
Celine George
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERSIMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
rajaselviazhagiri1
 
MICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdfMICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdf
DHARMENDRA SAHU
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Ad

Get Programming Python with CD 2nd Edition Mark Lutz free all chapters

  • 1. Visit https://ebookfinal.com to download the full version and explore more ebooks Programming Python with CD 2nd Edition Mark Lutz _____ Click the link below to download _____ https://ebookfinal.com/download/programming-python- with-cd-2nd-edition-mark-lutz/ Explore and download more ebooks at ebookfinal.com
  • 2. Here are some suggested products you might be interested in. Click the link to download Beginning Programming With Python For Dummies 1st Edition John Paul Mueller https://ebookfinal.com/download/beginning-programming-with-python-for- dummies-1st-edition-john-paul-mueller/ Distributed Programming with Ruby 1st Edition Mark Bates https://ebookfinal.com/download/distributed-programming-with-ruby-1st- edition-mark-bates/ Introduction to Computation and Programming Using Python with Application to Understanding Data 2nd edition Edition Guttag https://ebookfinal.com/download/introduction-to-computation-and- programming-using-python-with-application-to-understanding-data-2nd- edition-edition-guttag/ Hacking Secret Ciphers with Python A beginner s guide to cryptography and computer programming with Python 1st Edition Al Sweigart https://ebookfinal.com/download/hacking-secret-ciphers-with-python-a- beginner-s-guide-to-cryptography-and-computer-programming-with- python-1st-edition-al-sweigart/
  • 3. Active Grammar Level 3 with Answers and CD ROM 1st Edition Mark Lloyd https://ebookfinal.com/download/active-grammar-level-3-with-answers- and-cd-rom-1st-edition-mark-lloyd/ Black Hat Python Python Programming For Hackers And Pentesters 2nd Edition Justin Seitz And Tim Arnold https://ebookfinal.com/download/black-hat-python-python-programming- for-hackers-and-pentesters-2nd-edition-justin-seitz-and-tim-arnold/ Programming Google App Engine with Python Build and Run Scalable Python Apps on Google s Infrastructure 1st Edition Dan Sanderson https://ebookfinal.com/download/programming-google-app-engine-with- python-build-and-run-scalable-python-apps-on-google-s- infrastructure-1st-edition-dan-sanderson/ Expert Python Programming 1st Edition Tarek Ziade https://ebookfinal.com/download/expert-python-programming-1st-edition- tarek-ziade/ Deep Learning with Python 2nd Edition François Chollet https://ebookfinal.com/download/deep-learning-with-python-2nd-edition- francois-chollet/
  • 5. Programming Python with CD 2nd Edition Mark Lutz Digital Instant Download Author(s): Mark Lutz ISBN(s): 9780596000851, 0596000855 Edition: 2 File Details: PDF, 6.98 MB Year: 2001 Language: english
  • 6. Programming Python, 2nd Edition, O’Reilly IT-SC book 1 Programming Python, 2nd Edition Mark Lutz Publisher: O'Reilly 2nd Edition March 2001 ISBN: 0-596-00085-5, 1256 pages Programming Python focuses on advanced applications of Python. Endorsed by Python creator Guido van Rossum, it demonstrates advanced Python techniques, and addresses software design issues such as reusability and object- oriented programming. The enclosed platform-neutral CD- ROM (view CD-ROM content online at http://examples.oreilly.com/python2) has book examples and various Python-related packages, including the full Python Version 2.0 source code distribution.
  • 7. Programming Python, 2nd Edition, O’Reilly IT-SC book 2 Enjoy the life together.
  • 8. Programming Python, 2nd Edition, O’Reilly IT-SC book 3 Foreword Preface "And Now for Something Completely Different . . . Again" Signs of the Python Times Why This Edition? Major Changes in This Edition Using the Examples and Demos Conventions Used in This Book Where to Look for Updates Contacting O'Reilly Acknowledgments 1. Introducing Python 1.1 "And Now for Something Completely Different" 1.2 The Life of Python 1.3 The Compulsory Features List 1.4 What's Python Good For? 1.5 What's Python Not Good For? I: System Interfaces 2. System Tools 2.1 "The os.path to Knowledge" 2.2 Why Python Here? 2.3 System Scripting Overview 2.4 The sys Module 2.5 The os Module 2.6 Script Execution Context 2.7 Current Working Directory 2.8 Command-Line Arguments 2.9 Shell Environment Variables 2.10 Standard Streams 2.11 File Tools 2.12 Directory Tools 3. Parallel System Tools 3.1 "Telling the Monkeys What to Do" 3.2 Forking Processes 3.3 Threads 3.4 Program Exits 3.5 Interprocess Communication 3.6 Pipes 3.7 Signals 3.8 Launching Programs on Windows 3.9 Other System Tools 4. Larger System Examples I 4.1 "Splits and Joins and Alien Invasions" 4.2 Splitting and Joining Files 4.3 Generating Forward-Link Web Pages 4.4 A Regression Test Script 4.5 Packing and Unpacking Files
  • 9. Programming Python, 2nd Edition, O’Reilly IT-SC book 4 4.6 User-Friendly Program Launchers 5. Larger System Examples II 5.1 "The Greps of Wrath" 5.2 Fixing DOS Line Ends 5.3 Fixing DOS Filenames 5.4 Searching Directory Trees 5.5 Visitor: Walking Trees Generically 5.6 Copying Directory Trees 5.7 Deleting Directory Trees 5.8 Comparing Directory Trees II: GUI Programming 6. Graphical User Interfaces 6.1 "Here's Looking at You, Kid" 6.2 Python GUI Development Options 6.3 Tkinter Overview 6.4 Climbing the GUI Learning Curve 6.5 The End of the Tutorial 6.6 Python/Tkinter for Tcl/Tk Converts 7. A Tkinter Tour, Part 1 7.1 "Widgets and Gadgets and GUIs, Oh My!" 7.2 Configuring Widget Appearance 7.3 Toplevel Windows 7.4 Dialogs 7.5 Binding Events 7.6 Message and Entry 7.7 Checkbutton, Radiobutton, and Scale 7.8 Running GUI Code Three Ways 7.9 Images 8. A Tkinter Tour, Part 2 8.1 "On Today's Menu: Spam, Spam, and Spam" 8.2 Menus 8.3 Listboxes and Scrollbars 8.4 Text 8.5 Canvas 8.6 Grids 8.7 Time Tools, Threads, and Animation 8.8 The End of the Tour 8.9 The PyDemos and PyGadgets Launchers 9. Larger GUI Examples 9.1 "Building a Better Mouse Trap" 9.2 Advanced GUI Coding Techniques 9.3 Complete Program Examples 9.4 PyEdit: A Text Editor Program/Object 9.5 PyView: An Image and Notes Slideshow 9.6 PyDraw: Painting and Moving Graphics 9.7 PyClock: An Analog/Digital Clock Widget 9.8 PyToe: A Tic-Tac-Toe Game Widget
  • 10. Programming Python, 2nd Edition, O’Reilly IT-SC book 5 9.9 Where to Go from Here III: Internet Scripting 10. Network Scripting 10.1 "Tune in, Log on, and Drop out" 10.2 Plumbing the Internet 10.3 Socket Programming 10.4 Handling Multiple Clients 10.5 A Simple Python File Server 11. Client-Side Scripting 11.1 "Socket to Me!" 11.2 Transferring Files over the Net 11.3 Processing Internet Email 11.4 The PyMailGui Email Client 11.5 Other Client-Side Tools 12. Server-Side Scripting 12.1 "Oh What a Tangled Web We Weave" 12.2 What's a Server-Side CGI Script? 12.3 Climbing the CGI Learning Curve 12.4 The Hello World Selector 12.5 Coding for Maintainability 12.6 More on HTML and URL Escapes 12.7 Sending Files to Clients and Servers 13. Larger Web Site Examples I 13.1 "Things to Do When Visiting Chicago" 13.2 The PyMailCgi Web Site 13.3 The Root Page 13.4 Sending Mail by SMTP 13.5 Reading POP Email 13.6 Utility Modules 13.7 CGI Script Trade-offs 14. Larger Web Site Examples II 14.1 "Typos Happen" 14.2 The PyErrata Web Site 14.3 The Root Page 14.4 Browsing PyErrata Reports 14.5 Submitting PyErrata Reports 14.6 PyErrata Database Interfaces 14.7 Administrative Tools 14.8 Designing for Reuse and Growth 15. Advanced Internet Topics 15.1 "Surfing on the Shoulders of Giants" 15.2 Zope: A Web Publishing Framework 15.3 HTMLgen: Web Pages from Objects 15.4 JPython ( Jython): Python for Java 15.5 Grail: A Python-Based Web Browser 15.6 Python Restricted Execution Mode
  • 11. Programming Python, 2nd Edition, O’Reilly IT-SC book 6 15.7 XML Processing Tools 15.8 Windows Web Scripting Extensions 15.9 Python Server Pages 15.10 Rolling Your Own Servers in Python IV: Assorted Topics 16. Databases and Persistence 16.1 "Give Me an Order of Persistence, but Hold the Pickles" 16.2 Persistence Options in Python 16.3 DBM Files 16.4 Pickled Objects 16.5 Shelve Files 16.6 SQL Database Interfaces 16.7 PyForm: A Persistent Object Viewer 17. Data Structures 17.1 "Roses Are Red, Violets Are Blue; Lists Are Mutable, and So Is Class Foo" 17.2 Implementing Stacks 17.3 Implementing Sets 17.4 Binary Search Trees 17.5 Graph Searching 17.6 Reversing Sequences 17.7 Permuting Sequences 17.8 Sorting Sequences 17.9 Data Structures Versus Python Built-ins 17.10 PyTree: A Generic Tree Object Viewer 18. Text and Language 18.1 "See Jack Hack. Hack, Jack, Hack" 18.2 Strategies for Parsing Text in Python 18.3 String Module Utilities 18.4 Regular Expression Matching 18.5 Parser Generators 18.6 Hand-Coded Parsers 18.7 PyCalc: A Calculator Program/Object V: Integration 19. Extending Python 19.1 "I Am Lost at C" 19.2 C Extensions Overview 19.3 A Simple C Extension Module 19.4 The SWIG Integration Code Generator 19.5 Wrapping C Environment Calls 19.6 A C Extension Module String Stack 19.7 A C Extension Type String Stack 19.8 Wrapping C++ Classes with SWIG 20. Embedding Python 20.1 "Add Python. Mix Well. Repeat." 20.2 C Embedding API Overview 20.3 Basic Embedding Techniques
  • 12. Programming Python, 2nd Edition, O’Reilly IT-SC book 7 20.4 Registering Callback Handler Objects 20.5 Using Python Classes in C 20.6 ppembed: A High-Level Embedding API 20.7 Other Integration Topics VI: The End 21. Conclusion: Python and the Development Cycle 21.1 "That's the End of the Book, Now Here's the Meaning of Life" 21.2 "Something's Wrong with the Way We Program Computers" 21.3 The "Gilligan Factor" 21.4 Doing the Right Thing 21.5 Enter Python 21.6 But What About That Bottleneck? 21.7 On Sinking the Titanic 21.8 So What's Python: The Sequel 21.9 In the Final Analysis... 21.10 Postscript to the Second Edition A. Recent Python Changes A.1 Major Changes in 2.0 A.2 Major Changes in 1.6 A.3 Major Changes Between 1.3 and 1.5.2 B. Pragmatics B.1 Installing Python B.2 Book Examples Distribution B.3 Environment Configuration B.4 Running Python Programs B.5 Python Internet Resources C. Python Versus C++ Colophon
  • 13. Programming Python, 2nd Edition, O’Reilly IT-SC book 8 Foreword 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 ever-apart 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 gray-there 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 code-even many standard library modules-imports 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 time-although 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
  • 14. Programming Python, 2nd Edition, O’Reilly IT-SC book 9 into the current Python 2.x line of development, with a clear transition path that includes a period of backwards compatibility support. 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 3000-only 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 Life-that'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.
  • 15. Programming Python, 2nd Edition, O’Reilly IT-SC book 10 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 "And Now for Something Completely Different . . . Again" The first edition of this book was one of the first to present the Python language. This second edition is an almost completely new advanced Python topics book, designed to be a follow-up to the core language material in Learning Python and supplemented by the reference material in Python Pocket Reference. That is, this edition is focused on ways to use Python, rather than on the language itself. Python development concepts are explored along the way -- in fact, they really become meaningful only in the context of larger examples like those in this edition. But in general, this text now assumes that you already have at least a passing acquaintance with Python language fundamentals, and moves on to present the rest of the Python story. In this preface, I'll explain some of the rationales for this major rewrite, describe the structure of this edition in more detail, and give a brief overview of how to use the Python programs shipped on the enclosed CD-ROM (view CD-ROM content online at http://examples.oreilly.com/python2). First of all, though, a history lesson is in order. Signs of the Python Times It's been an exciting five years in the Python world. Since I wrote the first edition of this book between 1995 and 1996, Python has grown from a new kid on the scripting languages block to an established and widely used tool in companies around the world. Although measuring the popularity of an open source (http://opensource.org) and freely distributed tool such as Python is not always easy, most statistics available reveal exponential growth in Python's popularity over the last five years. Among the most recent signs of Python's explosive growth: Books As I write this in 2001, there are now over a dozen Python books on the market, with almost that many more on the way (in 1995 there were none). Some of these books are focused on a particular domain (e.g., Windows), and some are available in German, French, and Japanese language editions. Users In 1999, one leading industry observer suggested that there were as many as 300,000 Python users worldwide, based on various statistics. Other estimates are more optimistic still. In early 2000, for instance, the Python web site was already on track to service 500,000 new Python interpreter downloads by year end (in addition
  • 16. Programming Python, 2nd Edition, O’Reilly IT-SC book 11 to other Python distribution mediums); this figure is likely closer to the true user- base size as I write this book. Press Python is now regularly featured in industry publications. In fact, since 1995, Python creator Guido van Rossum has appeared on the cover of prominent tech magazines such as Linux Journal and Dr. Dobb's Journal; the latter publication gave him a programming excellence award for Python.[1] [1] As I was writing this book, Linux Journal also published a special Python supplement with their May 2000 edition -- the cover of which, of course, featured a naked man seated outdoors in front of a computer desk instead of a piano. If you don't know why that is funny, you need to watch a few reruns from Python's namesake, the Monty Python television series (consider it a first suggested exercise). I'll say more about the implications of Python's name in the first chapter. Applications Real companies have adopted Python for real products. It has shown up animating the latest Star Wars movie (Industrial Light & Magic), serving up maps and directories on the Internet (Yahoo), guiding users through Linux operating system installation (Red Hat), testing chips and boards (Intel), managing Internet discussion forums (Egroups), scripting online games (Origin), talking to CORBA frameworks (TCSI), implementing web site tools (Digital Creations' Zope), scripting wireless products (Agilent), and much more.[2] [2] See http://www.python.org for more details. Some companies don't disclose their Python use for competitive reasons, though many eventually become known when one of their web pages crashes and displays a Python error message in a browser. Hewlett Packard is generally counted among companies thus "outed." Newsgroup User traffic on the main Python Internet newsgroup, comp.lang.python, has risen dramatically too. For instance, according to eGroups (see http://www.egroups.com/group/python-list), there were 76 articles posted on that list in January 1994, and 2678 in January 2000 -- a 35-fold increase. Recent months have been busier still (e.g., 4226 articles during June, 2000 alone -- roughly 140 per day), and growth has been constant since the list's inception. This, and all other user-base figures cited in this preface, are likely to have increased by the time you read this text. But even at current traffic rates, Python forums are easily busy enough to consume the full-time attention of anyone with full-time attention to burn. Conferences There are now two annual Python conferences, one of which is hosted by O'Reilly & Associates. Attendance at Python conferences has roughly doubled in size every year. An annual Python Day is now also held in Europe. Group therapy Regional Python user groups have begun springing up in numerous sites in the U.S. and abroad, including Oregon, San Francisco, Washington D.C., Colorado, Italy,
  • 17. Programming Python, 2nd Edition, O’Reilly IT-SC book 12 Korea, and England. Such groups work on Python-related enhancements, organize Python events, and more. Domains Python has grown to embrace both Microsoft Windows developers, with new support for COM and Active Scripting, as well as Java developers, with the new JPython (renamed "Jython") Java-based implementation of the language. As we'll see in this edition, the new COM support allows Python scripts to be both component server and client; Active Scripting allows Python code to be embedded in HTML web page code and run on either client or server; and JPython compiles Python scripts to Java Virtual Machine code so that they can be run in Java-aware systems and can seamlessly integrate Java class libraries for use by Python code. As an open source tool for simplifying web site construction, the Python-based Zope web application framework discussed in this edition has also begun capturing the attention of webmasters and CGI coders. Services On the pragmatics front, commercial support, consulting, prepackaged distributions, and professional training for Python are now readily available from a variety of sources. For instance, the Python interpreter can be obtained on CDs and packages sold by various companies (including Walnut Creek, Dr. Dobb's Journal, and ActiveState), and Python usually comes prebuilt and free with most Linux operating system distributions. Jobs It's now possible to make money as a Python programmer (without having to resort to writing large, seminal books). As I write this book, the Python job board at http://www.python.org/Jobs.html lists some 60 companies seeking Python programmers in the U.S. and abroad. Searches for Python at popular employment sites yield even more hits -- for instance, 285 Python-related jobs on Monster.com, and 369 on dice.com. Not that anyone should switch jobs, of course, but it's nice to know that you can now make a living by applying a language that also happens to be a pleasure to use. Tools Python has also played host to numerous tools development efforts. Among the most prominent as I write these words: the Software Carpentry project, which is developing new core software tools in Python; ActiveState, which ison the verge of releasing a set of Windows and Linux-focused Python development products; and PythonWare, which is about to release an integrated Python development environment and GUI builder. Compilers As I write this preface, ActiveState has also announced a new Python compiler for the Microsoft .NET framework and C# language environment -- a true Python compiler and independent implementation of the Python language that generates DLL and EXE files, allows Python code to be developed under Visual Studio, and provides seamless .NET integration for Python scripts. It promises to be a third
  • 18. Programming Python, 2nd Edition, O’Reilly IT-SC book 13 implementation of Python, along with the standard C-based Python, and the JPython Java-based system. Education Python has also begun attracting the attention of educators, many of whom see Python as a "Pascal of the 2000s" -- an ideal language for teaching programming, due to its simplicity and structure. Part of this appeal was spawned by Guido van Rossum's proposed Computer Programming for Everybody (CP4E) project, aimed at making Python the language of choice for first-time programmers worldwide. At this writing the future of CP4E itself is uncertain, but a Python special interest group (SIG) has been formed to address education-related topics. Regardless of any particular initiative's outcome, Python promises to make programming more accessible to the masses of people who will surely soon grow tired of clicking preprogrammed links, as they evolve from computer users to computer scripters. In other words, it's not 1995 anymore. Much of the preceding list was unimaginable when the first edition of this book was conceived. Naturally, this list is doomed to be out of date even before this book hits the shelves, but it is nonetheless representative of the sorts of milestones that have occurred over the last five years, and will continue to occur for years to come. As a language optimized to address the productivity demands of today's software world, Python's best is undoubtedly yet to come. So What's Python? If you 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. Among other things, Python sports object-oriented programming (OOP); a remarkably simple, readable, and maintainable syntax; integration with C components; and a vast collection of precoded interfaces and utilities. Although general-purpose, 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.
  • 19. Programming Python, 2nd Edition, O’Reilly IT-SC book 14 Why This Edition? One consequence of the growing popularity of Python has been an influx of new users, programming styles, and applications, all of which have conspired to make parts of the first edition of this book prime for updates. Python itself has changed in smaller ways, but important extensions have simplified various aspects of Python development and merit new coverage. Perhaps most relevant for this edition is that the Python "audience" has changed. Over the last five years, Python has transitioned from an emerging language of interest primarily to pioneers to a widely accepted tool used by programmers for day-to-day development tasks. This edition has been refocused for this new Python audience. You will find that it is now more of a nuts-and-bolts text, geared less toward introducing and popularizing the language than to showing how to apply it for realistically scaled programming tasks. Because of the breadth of change, this edition is something of an entirely new book. To readers who enjoyed the first edition, I would like to express my gratitude, and I hope you will find the same spirit in this second edition. Although this is a major rewrite, I have tried to retain as much of the original book's material and flavor as possible (especially the jokes :-). Since writing the first edition five years ago, I have also had the opportunity to teach Python classes in the U.S. and abroad, and some of the new examples reflect feedback garnered from these training sessions. The new application domain examples reflect common interests and queries of both myself and my students. 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 edition's examples and topics. Other new examples are simply the result of my having fun programming Python. Yes, fun; I firmly believe that one of Python's greatest intangible assets is its ability both to kindle the excitement of programming among newcomers, and to rekindle the excitement among those who have toiled for years with more demanding tools. As we will see in this edition, Python makes it incredibly easy to play with advanced but practical tools such as threads, sockets, GUIs, web sites, and OOP -- areas that can be both tedious and daunting in traditional compiled languages like C and C++. Frankly, even after eight years as a bona fide Pythonista, I still find programming most enjoyable when it is done in Python. Python is a wildly productive language, and witnessing its application first-hand is an aesthetic delight. I hope this edition, as much as the first, will demonstrate how to reap Python's productivity benefits and communicate some of the satisfaction and excitement found in a rapid-development tool such as Python. Major Changes in This Edition 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 first edition, the next few sections go into more detail about what is new in this edition.
  • 20. Programming Python, 2nd Edition, O’Reilly IT-SC book 15 It's Been Updated for Python 2.0 This edition has been updated for Python 2.0, and the Graphical User Interface (GUI) material has been updated for Tk versions 8.0 or later. Technically, this update was begun under Python 1.5.2, but all examples were revisited for 2.0 before publication. For the trivia buffs among you: release 2.0 was the first Python release following Guido's move to BeOpen, while 1.6 was the last release from Guido's prior employer, CNRI. Just before I finished this book's final draft and after the 2.0 release, Guido and the core Python development team moved from BeOpen to Digital Creations, home of the Zope web application construction kit, but this move is independent of Python releases (see Chapter 1, for more details). Release 2.0 introduces a few language extensions, but 2.0 and 1.6 are similar in content, and the updates just add a handful of features. The examples in this book should generally work with later Python releases. Remarkably, almost all examples in the first edition still work five years later, with the latest Python releases; those that didn't work required only small fixes (e.g., GUI call formats and C API interfaces). On the other hand, although the core language hasn't changed much since the first edition, a number of new constructs have been added, and we'll apply them all here. Among these new Python features: module packages, class exceptions, pseudo- private class attributes, unicode strings, the new regular expression module, new Tkinter features such as the grid manager, standard dialogs, and top-level menus, and so on. A new appendix summarizes all of the major changes in Python between the first and second editions of this book. In addition to the language changes, this book presents new Python tools and applications that have emerged in recent years. Among them: the IDLE programming interface, the JPython (a.k.a. "Jython") compiler, Active Scripting and COM extensions, the Zope web framework, Python Server Pages (PSP), restricted execution mode, the HTMLgen and SWIG code generators, thread support, CGI and Internet protocol modules, and more (it's been a busy five years). Such applications are the heart and soul of this second edition. It's Been Refocused for a More Advanced Audience This edition presents Python programming by advanced examples. Becoming proficient in Python involves two distinct tasks: learning the core language itself, and then learning how to apply it in applications. This edition addresses the latter (and larger) of these tasks by presenting Python libraries, tools, and programming techniques. Since this is a very different focus, I should say a few words about its rationale here. Because there were no other Python books on the horizon at the time, the first edition was written to appeal to many audiences at once -- beginners and gurus alike. Since then, another O'Reilly book, Learning Python, has been developed to address the needs of beginners, and Python Pocket Reference was published for readers seeking a short Python reference. As a result, the core language introductory-level material and the original reference appendixes have been removed from this book.
  • 21. Programming Python, 2nd Edition, O’Reilly IT-SC book 16 Learning Python introduces the core language -- its syntax, datatypes, and so on -- using intentionally simplistic examples. Many have found it to be ideal for learning the language itself, but Python can become even more interesting once you master the basic syntax and can write simple examples at the interactive prompt. Very soon after you've learned how to slice a list, you 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. Programming Python focuses on the "everything else" of Python development. 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 only be illustrated in the context of realistically scaled programs. In other words, Programming Python, especially in this new edition, is designed to pick up where Learning Python leaves off. Therefore, if you find this book too advanced, I encourage you to read Learning Python as a prelude to this text, and return here for the rest of the story once you've mastered the basics. Unless you already have substantial programming experience, this edition might serve you best as a second Python text. It Covers New Topics Most of the changes in this edition were made to accommodate new topics. There are new chapters and sections on Internet scripting, CGI scripts, operating system interfaces, the SWIG integration code generator, advanced Tkinter topics, the HTMLgen web page generator, JPython, threads, restricted execution mode, and more. You should consult the Table of Contents for the full scoop, but here are some of the new topics and structural changes you'll find in this edition: Topics The Internet, systems programming, Tkinter GUIs, and C integration domains get much more attention, and are arguably now the main focus of this text. For instance, you'll find six new chapters on Internet scripting, covering client-side tools, server- side scripts and web sites, and advanced Internet topics and systems. Four new chapters address systems topics: threads, directory processing, program launching, and so on. And the GUI material has also grown from one chapter to a much more complete four-chapter presentation, and now covers all widgets (including text and canvas), as well as new grid, menu, and dialog support. C integration The C extending and embedding chapters have been expanded to cover new topics such as SWIG (the way to mix Python with C/C++ libraries today) and present new mixed-mode examples such as callback dispatch (extending plus embedding). C integration is at the heart of many Python systems, but the examples in this domain are inevitably complex, and involve large C programs that are only useful to C users. In deference to readers who don't need to code C integrations, this material is now isolated at the end of the text. Some of the C code listings are gone as well -- to reduce page count, I have opted instead to point readers to C source files on the enclosed CD-ROM where possible (see http://examples.oreilly.com/python2).
  • 22. Programming Python, 2nd Edition, O’Reilly IT-SC book 17 Although later chapters build upon material in earlier chapters, topics in this edition are covered fairly independently, and are associated by book parts. Because of that, it's not too much of a stretch to consider this edition to be akin to four or five books in one. Its top-level structure underscores its application topics focus: Preface (you are here) Chapter 1 Part I Chapter 2 Chapter 3 Chapter 4 Chapter 5 Part II Chapter 6 Chapter 7 Chapter 8 Chapter 9 Part III Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Part IV Chapter 16 Chapter 17 Chapter 18 Part V Chapter 19 Chapter 20 Part VI Chapter 21 Appendix A Appendix B Appendix C Two notes here: First of all, don't let these titles fool you -- although 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. Second, readers who use Python as a standalone tool can safely skip the integration chapters, though I still recommend a quick glance. C programming isn't nearly as fun or easy as Python programming. 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. First edition readers will notice that most of this material is new, and even chapters with old titles contain largely new material. Noticeably absent in this edition are the original Sneak Preview, Mini Reference, Tutorial Appendix, and all of the old Part II -- a reflection of the new focus and intended readership. It's More Example-Oriented
  • 23. Programming Python, 2nd Edition, O’Reilly IT-SC book 18 This book is largely about its examples. In this edition, old examples have been extended to become more realistic (e.g., PyForm and PyCalc), and new examples have been added throughout. Among the major examples, you'll find: 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 A tree data structure 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 PyMail A Python/Tk POP and SMTP email client PyFtp A simple Python/Tk file-transfer GUI PyErrata A web-based error report system PyMailCgi A web-based email interface
  • 24. Programming Python, 2nd Edition, O’Reilly IT-SC book 19 There are also new 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 new socket and select module examples), many new examples of Python threads, and new coverage of JPython, HTMLgen, Zope, Active Scripting, COM, and Python database interfaces. Many of the new examples are somewhat advanced, but of course this is now a somewhat advanced text. In addition, the old Python/C embedding API (now called ppembed ) has been extended to support precompiling strings to bytecode, and the original calculator example (now called PyCalc) has been beefed up to support keyboard entry, history lists, colors, and more. In fact, the new book examples tree distributed on this edition's CD-ROM (see http://examples.oreilly.com/python2) is itself a fairly sophisticated Python software system, and the examples within it have been upgraded structurally in a number of important ways: Examples tree The entire examples distribution has been organized as one big Python module package to facilitate cross-directory imports and avoid name-clashes with other Python code installed on your computer. Using directory paths in 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 PP2E examples root directory. To reuse code in this book within your own applications, simply import through the PP2E package root (e.g., from PP2E.Launcher import which). Example filenames Module names are generally much less cryptic now. I punted on 8.3 DOS compatibility long ago, and use more descriptive filenames. I've also fixed some old all-uppercase filenames, which were a last vestige of MS-DOS. Example titles Labels of example listings now 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: PP2EInternetFtpsousa.py refers to the file sousa.py in the PP2EInternetFtp subdirectory of the examples distribution directory.[4] [4] The "examples distribution directory" is the directory containing the top-level PP2E directory of the book examples tree. On the CD (see http://examples.oreilly.com/python2), it's the topmost Examples directory; if you've copied the examples to your machine, it's wherever you copied (or unpacked) the PP2E root directory. You can run most of the examples from the CD directly, but you'll want to copy them to your hard drive to make changes, and to allow Python to save .pyc compiled bytecode files for quicker startups. Example command lines
  • 25. Programming Python, 2nd Edition, O’Reilly IT-SC book 20 Similarly, when a command line is shown typed after a prompt such as C:...PP2ESystemStreams>, for example, it is really to be typed in the PP2ESystemStreams subdirectory in your examples tree. Unix and Linux users: please think / when you see in filename paths (my official excuse for which is outlined in the next section). Example launchers Because it's just plain fun to click on things right away, there are new self- configuring demo launcher programs (described later in this preface in Section P.5.1), to give you a quick look at Python scripts in action with minimal configuration requirements. You can generally run them straight off the book's CD without setting any shell variables first. It's More Platform-Neutral Except for some C integration examples, the majority of the programs in this edition were developed on my Windows 98 laptop, 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 Red Hat Linux 6.x platform only if they exercise Unix-specific interfaces. This is not a political statement at all -- I like Linux too. It's mostly a function of the fact that I wrote this book with MS Word; when time is tight, it's more convenient to run scripts on the same platform as your publishing tools than to frequently reboot into Linux. Luckily, because Python has now become so portable to both Windows and Linux, the underlying operating system is less of a concern to Python developers than it once was. Python, its libraries, and its Tkinter GUI framework all work extremely well on both platforms today. Because I'm not a politician, though, I've tried to make the examples as platform- neutral as possible, and point out platform-specific issues along the way. Generally speaking, most of the scripts should work on common Python platforms unchanged. For instance, all the GUI examples were tested on both Windows (98, 95) 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 generally built to be portable, this is easier than it may sound. On the other hand, this book does delve into platform-specific topics where appropriate. There is new coverage of many Windows-specific topics -- Active Scripting, COM, program launch options, and so on. Linux and Unix readers will also find material geared towards their platforms -- forks, pipes, and the like. There is also new discussion of ways to edit and run Python programs on most major platforms. 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-biased. One can at least make a reasonable case for such a focus -- not only does Linux come with C compilers for free, but its development environment grew up around that language. On Windows, the C extension code shown in this book will work, but you may need to use different build
  • 26. Programming Python, 2nd Edition, O’Reilly IT-SC book 21 procedures that vary per Windows compiler. O'Reilly has published an outstanding text, Python Programming on Win32, that covers Windows-specific Python topics like this, and should help address some of the disparity here. If you do Windows-specific programming, please see that book for all Windows details skipped here. But It's Still Not a Reference Manual Please note that 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 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 contents. For an exhaustive list of all tools available in the Python system, consult other books (e.g., O'Reilly's Python Pocket Reference) or the standard manuals at Python's web site and on this book's CD-ROM (see http://examples.oreilly.com/python2). Using the Examples and Demos I want to briefly describe how to use the book's examples here. In general, though, please see the following text files in the examples distribution directory for more details: README-root.txt: package structure notes PP2EREADME-PP2E.txt: general usage notes PP2EConfigsetup-pp.bat: Windows configuration PP2EConfigsetup-pp.csh: Unix and Linux configuration Of these, the README-PP2E.txt file is the most informative, and the PP2EConfig directory contains all configuration file examples. I give an overview here, but the files listed give a complete description. The Short Story If you want to see some Python examples right away, do this: Install Python from the book's CD-ROM (see http://examples.oreilly.com/python2), unless it is already installed on your computer. On Windows, click on the name of the self-installer program on the CD and do a default install (say "yes" or "next" to every prompt). On other systems, see the README file (the gzipped source distribution on the CD can be used to build Python locally).
  • 27. Programming Python, 2nd Edition, O’Reilly IT-SC book 22 Start one of the following self-configuring scripts located in the top-level ExamplesPP2E directory on the CD (see http://examples.oreilly.com/python2). Either click on their icons in your file explorer, or run them from your system prompt (e.g., DOS console box, Linux Xterm) using command lines of the form python script-name (you may need to use the full path to python if it's not 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 standard Python/Tk utilities LaunchBrowser.py: opens web examples index in web browser The Launch_* scripts start Python programs portably[5] and require only that Python be installed -- you don't need to set environment variables first or tweak the included PP2EConfig setup files 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). [5] All the demo and launcher scripts are written portably but are known to work only on Windows 95/98 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, X11, and Macs; Python itself runs on everything from handheld PDAs to mainframes; and my advance for writing this book wasn't as big as you may think. If installing Python isn't an option, you can still run a few Python web demos by visiting http://starship.python.net/~lutz/PyInternetDemos.html with your browser. Because these examples execute scripts on a server, they tend to work best when run live from this site, rather than from the book's CD. The Details To help organize the new examples, I've provided a demo launcher program, PyDemos.pyw, in the top-level PP2E directory of the examples distribution. Figure P- 1 shows PyDemos in action on Windows after pressing a few buttons. The launcher bar appears on the left of the screen; with it, you can run most of the major graphical examples in the book with a mouse click. The demo launcher bar can also be used to start major Internet book examples if a browser can be located on your machine (see the following launcher description). Besides launching demos, the PyDemos source code provides pointers to major examples in the distribution; see its source code for details. You'll also find Linux automated build scripts for the Python/C integration examples in the top-level examples directory, which serve as indexes to major C examples. Figure P-1. The PyDemos launcher with pop-ups and demos (Guido's photo reprinted with permission from Dr. Dobb's Journal)
  • 28. Programming Python, 2nd Edition, O’Reilly IT-SC book 23 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 often; configure as desired). Figure P-2 shows what PyGadgets_bar looks like on Windows, along with a few of the utilities that its buttons can launch. All of the programs are presented in this book and included in the examples distribution. Most gadgets require a Python with Tkinter support, but that is the default configuration for the standard Windows port on the book's CD (see http://examples.oreilly.com/python2). Figure P-2. The PyGadgets utilities launcher bar, with gadgets
  • 29. Programming Python, 2nd Edition, O’Reilly IT-SC book 24 To run the files listed in the prior paragraph directly, you'll need to set up your Python module search path (see the top-level PP2E/Config/setup* files for hints). But if you want to run a collection of Python demos from the book and don't want to bother with setting up your environment first, simply run the self-launching utility scripts in the PP2E directory instead: Launch_PyDemos.pyw, Launch_PyGadgets.py, and Launch_PyGadgets_bar.pyw. 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 the demos. You can probably run these launch scripts by simply clicking on their names in a file explorer, and you should also be able to run them directly from the book's CD-ROM (see http://examples.oreilly.com/python2). See the comments at the top of Launcher.py for more details (or read about these scripts in Chapter 4 ). Many of the browser-based Internet examples from the book can also be found online at http://starship.python.net/~lutz/PyInternetDemos.html, where you can test-drive a few Python Internet scripting examples. Because these examples run in your web browser, they can be tested even if you haven't installed Python (or Python's Tk support) on your machine. The PyDemos program also attempts to launch a web browser on the major example web pages by starting 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. Provided LaunchBrowser can find a browser on your machine, some demo buttons will pop up web pages automatically, whether you have a live Internet connection or not (if not, you'll see local files in your browser). Figure P-3 shows what the PyInternetDemos page looks like under Internet Explorer on Windows.
  • 30. Programming Python, 2nd Edition, O’Reilly IT-SC book 25 Figure P-3. The PyInternetDemos web page Of special interest, the getfile.html link on this page allows you to view the source code of any other file on the book's site -- HTML code, Python CGI scripts, and so on; see Chapter 12 for details. To summarize, here is what you'll find in the top-level PP2E directory of the book's examples distribution: PyDemos.pyw Button bar for starting major GUI and Internet examples PyGadgets.py Starts programs in non-demo mode for regular use PyGadgets_bar.pyw Button bar for starting PyGadgets on demand Launch_*.py* Starts PyDemos and PyGadgets programs using Launcher.py to autoconfigure search paths (run these for a quick look) Launcher.py
  • 31. Programming Python, 2nd Edition, O’Reilly IT-SC book 26 Used to start programs without environment settings -- finds Python, sets PYTHONPATH, spawns Python programs LaunchBrowser.py Opens example web pages with an automatically located web browser, either live off the Net or by opening local web page files; if started directly, opens the PyInternetDemos index page There are also subdirectories for examples from each major topic area of the book. In addition, the top-level PP2EPyTools 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 the book's CD (see http://examples.oreilly.com/python2), deleting old .pyc bytecode files in the tree, and more. Again, see the distribution's README-PP2E.txt file for more details on all example issues. Where It's At The book examples distribution can be found on the CD-ROM that accompanies this book. See the CD's top-level README file for usage details, or browse the CD's example root directory in your favorite file explorer for a quick tour. In addition to the book examples, the CD also contains various Python-related packages, including a full Windows self-installer program with Python and Tk support (double-click and say "yes" at all prompts to install), the full Python source code distribution (unpack and compile on your machine), and Python's standard documentation set in HTML form (click to view in your web browser). Extra open source packages such as the latest releases (at the time of publication) of the SWIG code generator and JPython are also included, but you can always find up- to-date releases of Python and other packages at Python's web site, http://www.python.org. Conventions Used in This Book The following font conventions are used in this book: Italic Used for file and directory names, commands, 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
  • 32. Programming Python, 2nd Edition, O’Reilly IT-SC book 27 Constant width italic Used to mark replaceables This icon designates a note related to the nearby text. This icon designates a warning related to the nearby text. 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 second edition's link on that page for all supplemental information related to this version of the book. As for the first edition, I will also be maintaining a log on this web site of Python changes over time, which you should consider a supplement to this text. Beginning with this edition, I am making available a user-driven book errata reporting system on the World Wide Web, at this site: http://starship.python.net/~lutz/PyErrata/pyerrata.html There, you'll find forms for submitting book problem reports and comments, as well as viewing the report database by various sort keys. Reports are stored in a publicly browsable database by default, but an option lets you email them privately instead. The PyErrata system also happens to be written in Python, and is an example presented and shipped with this book; see Chapter 14. Figure P-4 shows what the root page of PyErrata looks like. Figure P-4. The PyErrata book updates site
  • 33. Programming Python, 2nd Edition, O’Reilly IT-SC book 28 If any of these addresses stop working over time, these pages might also be accessible from O'Reilly's web site, http://www.oreilly.com.[6] I'm still happy to receive direct emails from readers, of course, but the PyErrata site will hopefully streamline the report-posting process. [6] O'Reilly has an errata report system at their site too, 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 & Associates, Inc. 101 Morris Street Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (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: http://www.oreilly.com/catalog/python2/ To comment or ask technical questions about this book, send email to: [email protected]
  • 34. Programming Python, 2nd Edition, O’Reilly IT-SC book 29 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
  • 35. Programming Python, 2nd Edition, O’Reilly IT-SC book 30 Acknowledgments In addition to the people I mentioned in the first edition's preface, I'd like to extend appreciation to a few of the people who helped in some way during this second edition project: To this book's first editor, Frank Willison, for overseeing this update, as well as championing the Python cause at O'Reilly and beyond. To this book's later editor, Laura Lewin, for picking up the ball and lighting necessary fires. To Python creator Guido van Rossum for making this stuff fun again. To the people who took part in a review of an early draft of this edition: Eric Raymond, Mark Hammond, David Ascher, Tim Peters, and Dave Beazley. To Tim O'Reilly and the staff of O'Reilly & Associates, both for producing this book, and supporting open source software in general. To the Python community at large, for diligence, hard work, and humor -- both in the early years and today. We've come far, but to steal a line from the 1970s: You aint' seen nothin' yet. And to the students of the many Python classes I have taught, as well as the scores of readers who took the time to send me comments about the first edition; your opinions helped shape this update. Finally, a few personal notes of thanks. To my children, Michael, Samantha, and Roxanne, for purpose. If they are at all representative of their generation, the future of our species seems in very good hands. You'll have to pardon me if that sounds proud; with kids like mine, it's impossible to feel otherwise. And most of all to Lisa, the mother of those amazing kids. I owe her my largest debt of gratitude, for everything from enduring my flights from reality while writing books like this, to keeping me out of jail in our youth. No matter what the future may hold, I'll always be glad that something threw us together two decades ago. Mark Lutz November 2000 Somewhere in Colorado "When Billy Goes Down, He's Going Down Fast" The last five years have also been host to the rise of the open source movement. Open source refers to software that is distributed free of charge with full source code, and is usually the product of many developers working in a loosely knit collaborative fashion. Python, the Linux operating system, and many other tools such as Perl and the Apache web server fall into this category. Partly because of its challenge to the dominance of mega- companies, the open source movement has quickly spread through society
  • 36. Programming Python, 2nd Edition, O’Reilly IT-SC book 31 in profound ways. Let me tell you about an event that recently underscored the scope of this movement's impact on me. To understand this story, you first need to know that as I was writing this book, I lived in a small town in Colorado not generally known for being on the cutting edge of technological innovation. To put that more colorfully, it's the sort of place that is sometimes called a "cowboy town." I was at a small local bookstore hunting for the latest Linux Journal. After browsing for a while, I found a copy and walked it to the checkout. Behind the counter were two clerks who looked as if they might be more at home at a rodeo than behind the counter of this establishment. The older of the two sported gray hair, a moustache, and the well-worn skin of a person accustomed to life on a ranch. Both wore obligatory baseball caps. Cowboys, to be sure. As I put the magazine down, the elder clerk looked up for a moment, and said, in classic cowboy drawl, "Linux, huh? I tell you what, when Billy goes down, he's goin' down fast!" Of course, this was in reference to the widely publicized competition between Linux and Bill Gates' Microsoft Windows, spurred by the open source movement. Now, in another time and place, these two might have instead been discussing livestock and firearms over strong cups of coffee. Yet somehow, somewhere, they had become passionate advocates of the Linux open source operating system. After collecting my chin from the floor, we wound up having a lively discussion about Linux, Microsoft, Python, and all things open. You might even say we had a good-old time. I'm not trying to express a preference for one operating system over another here; both have merits, and Python runs equally well on either platform (indeed, this book's examples were developed on both systems). But I am amazed that an idea that software developers often take for granted has had such a deep, mainstream impact. That seems a very hopeful thing to me; if technology is to truly improve the quality of life in the next millennium, we need all the cowboys we can get.
  • 37. Programming Python, 2nd Edition, O’Reilly IT-SC book 32 Chapter 1. Introducing Python 1.1 "And Now for Something Completely Different" 1.2 The Life of Python 1.3 The Compulsory Features List 1.4 What's Python Good For? 1.5 What's Python Not Good For? 1.1 "And Now for Something Completely Different" This book is about using Python, a very high-level, object-oriented, open source[1] programming language, designed to optimize development speed. Although it is completely general-purpose, Python is often called an object-oriented 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. [1] 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 half a million users in that community today, Python is very well supported. 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 nontechnical 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 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: Quality Python makes it easy to write software that can be reused and maintained. It was deliberately designed to raise development quality expectations in the scripting world. Python's clear syntax and coherent design almost forces programmers to write readable code -- a critical feature for software that may be changed by others. The Python language really does look like it was designed, not accumulated. Python is also well tooled for modern software reuse methodologies. In fact, writing high- quality Python components that may be applied in multiple contexts is almost automatic. Productivity
  • 38. Programming Python, 2nd Edition, O’Reilly IT-SC book 33 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 lower- level languages. Things like type declarations, memory management, and build procedures are nowhere to be found in Python scripts. 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 long after they have been written. In addition, Python supports (but does not impose) advanced paradigms such as object-oriented programming, which further boost developer productivity and shrink development schedules. Portability Most Python programs run without change on almost every computer system in use today. In fact, Python programs run today on everything from IBM mainframes and Cray Supercomputers to notebook PCs and handheld PDAs. Although some platforms offer nonportable extensions, the core Python language and libraries are platform- neutral. For instance, most Python scripts developed on Linux will generally run on Windows immediately, and vice versa -- simply copy the script over. Moreover, a graphical user interface (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 at all. Integration Python is designed to be integrated with other tools. Programs written in Python can be easily mixed with and script (i.e., direct) other components of a system. Today, for example, Python scripts can call out to existing C and C++ libraries, talk to Java classes, integrate with COM and CORBA components, 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 servers, and so on. Python is not a closed box. In an era of increasingly short development schedules, faster machines, and heterogeneous applications, these strengths have proven to be powerful allies 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, libraries of precoded tools to minimize up-front development, and completely free nature that cuts product development and deployment costs. But Python's productivity focus is perhaps its most attractive and defining quality. As I write this, the main problem facing the software development world is not just writing programs quickly, but finding developers with time to write programs at all. Developers' time has become paramount -- much more critical than execution speed. There are simply more projects than programmers to staff them. As a language optimized for developer productivity, Python seems to be the right answer to the questions being asked by the development world. Not only can Python developers implement systems quickly, but the resulting systems will be maintainable, portable, and easily integrated with other application components.
  • 39. Programming Python, 2nd Edition, O’Reilly IT-SC book 34 1.2 The Life of Python Python was invented around 1990 by Guido van Rossum, when he was at CWI in Amsterdam. Despite the reptiles, it is named after the BBC comedy series Monty Python's Flying Circus, of which Guido is a fan (see the following silly sidebar). Guido was also involved with the Amoeba distributed operating system and the ABC language. In fact, the original motivation for Python was to create an advanced scripting language for the Amoeba system. But Python's design turned out to be general enough to address a wide variety of domains. It's now used by hundreds of thousands of engineers around the world, in increasingly diverse roles. Companies use Python today in commercial products, for tasks such as testing chips and boards, developing GUIs, searching the Web, animating movies, scripting games, serving up maps and email on the Internet, customizing C++ class libraries, and much more.[2] In fact, because Python is a completely general-purpose language, its target domains are only limited by the scope of computers in general. [2] See the preface for more examples of companies using Python in these ways, and see http://www.python.org for a more comprehensive list of commercial applications. Since it first appeared on the public domain scene in 1991, Python has continued to attract a loyal following, and spawned a dedicated Internet newsgroup, comp.lang.python, in 1994. And as the first edition of this book was being written in 1995, Python's home page debuted on the WWW at http://www.python.org -- still the official place to find all things Python. What's in a Name? Python gets its name from the 1970s British TV comedy series, Monty Python's Flying Circus. According to Python folklore, Guido van Rossum, Python's creator, was watching reruns of the show at about the same time he needed a name for a new language he was developing. And, as they say in show business, "the rest is history." Because of this heritage, references to the comedy group's work often show up in examples and discussion. For instance, the name "Spam" has a special connotation to Python users, and confrontations are sometimes referred to as "The Spanish Inquisition." As a rule, if a Python user starts using phrases that have no relation to reality, they're probably borrowed from the Monty Python series or movies. Some of these phrases might even pop up in this book. You don't have to run out and rent The Meaning of Life or The Holy Grail to do useful work in Python, of course, but it can't hurt. While "Python" turned out to be a distinctive name, it's also had some interesting side effects. For instance, when the Python newsgroup, comp.lang.python, came online in 1994, its first few weeks of activity were almost entirely taken up by people wanting to discuss topics from the TV show. More recently, a special Python supplement in the Linux Journal magazine featured photos of Guido garbed in an obligatory "nice red
  • 40. Programming Python, 2nd Edition, O’Reilly IT-SC book 35 uniform." There's still an occasional post from fans of the show on Python's news list. For instance, one poster innocently offered to swap Monty Python scripts with other fans. Had he known the nature of the forum, he might have at least mentioned whether they ran under DOS or Unix. To help manage Python's growth, organizations aimed at supporting Python developers have taken shape over the years: among them, 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. Although the future of the PSA is unclear as I write these words, it has helped to support Python through the early years. Today, Guido and a handful of other key Python developers, are employed by a company named Digital Creations to do Python development on a full-time basis. Digital Creations, based in Virginia, is also home to the Python-based Zope web application toolkit (see http://www.zope.org). However, the Python language is owned and managed by an independent body, and remains a true open source, community-driven system. Other companies have Python efforts underway as well. For instance, ActiveState and PythonWare develop Python tools, O'Reilly (the publisher of this book) and a company named Foretech both organize annual Python conferences, and O'Reilly manages a supplemental Python web site (see the O'Reilly Network's Python DevCenter at http://www.oreillynet.com/python). The O'Reilly Python Conference is held as part of the annual Open Source Software Convention. Although the world of professional organizations and companies changes more frequently than do published books, it seems certain that the Python language will continue to meet the needs of its user community. 1.3 The Compulsory Features List One way to describe a language is by listing its features. Of course, this will be more meaningful after you've seen Python in action; the best I can do now is speak in the abstract. And it's really how Python's features work together, that make it what it is. But looking at some of Python's attributes may help define it; Table 1-1 lists some of the common reasons cited for Python's appeal. Table 1-1. Python Language Features Features Benefits No compile or link steps Rapid development cycle turnaround No type declarations Simpler, shorter, and more flexible programs
  • 41. Programming Python, 2nd Edition, O’Reilly IT-SC book 36 Automatic memory management Garbage collection avoids bookkeeping code High-level datatypes and operations Fast development using built-in object types Object-oriented programming Code reuse, C++, Java, and COM integration Embedding and extending in C Optimization, customization, system "glue" Classes, modules, exceptions Modular "programming-in-the-large" support A simple, clear syntax and design Readability, maintainability, ease of learning Dynamic loading of C modules Simplified extensions, smaller binary files Dynamic reloading of Python modules Programs can be modified without stopping Universal "first-class" object model Fewer restrictions and special-case rules Runtime program construction Handles unforeseen needs, end-user coding Interactive, dynamic nature Incremental development and testing Access to interpreter information Metaprogramming, introspective objects Wide interpreter portability Cross-platform programming without ports Compilation to portable bytecode Execution speed, protecting source code Standard portable GUI framework Tkinter scripts run on X, Windows, and Macs Standard Internet protocol support Easy access to email, FTP, HTTP, CGI, etc.
  • 42. Programming Python, 2nd Edition, O’Reilly IT-SC book 37 Standard portable system calls Platform-neutral system scripting Built-in and third-party libraries Vast collection of precoded software components True open source software May be freely embedded and shipped To be fair, Python is really a conglomeration of features borrowed from other languages. It includes elements taken from C, C++, Modula-3, ABC, Icon, and others. For instance, Python's modules came from Modula, and its slicing operation from Icon (as far as anyone can seem to remember, at least). And because of Guido's background, Python borrows many of ABC's ideas, but adds practical features of its own, such as support for C-coded extensions. 1.4 What's Python Good For? Because Python is used in a wide variety of ways, it's almost impossible to give an authoritative answer to this question. In general, any application that can benefit from the inclusion of a language optimized for speed of development is a good target Python application domain. Given the ever-shrinking schedules in software development, this a very broad category. A more specific answer is less easy to formulate. For instance, some use Python as an embedded extension language, while others use it exclusively as a standalone programming tool. And to some extent, this entire book will answer this very question -- it explores some of Python's most common roles. For now, here's a summary of some of the more common ways Python is being applied today: System utilities Portable command-line tools, testing systems Internet scripting CGI web sites, Java applets, XML, ASP, email tools Graphical user interfaces With APIs such as Tk, MFC, Gnome, KDE Component integration C/C++ library front-ends, product customization Database access Persistent object stores, SQL database system interfaces
  • 43. Programming Python, 2nd Edition, O’Reilly IT-SC book 38 Distributed programming With client/server APIs like CORBA, COM Rapid-prototyping /development Throwaway or deliverable prototypes Language-based modules Replacing special-purpose parsers with Python And more Image processing, numeric programming, AI, etc. "Buses Considered Harmful" The PSA organization described earlier was originally formed in response to an early thread on the Python newsgroup, which posed the semiserious question: "What would happen if Guido was hit by a bus?" These days, Guido van Rossum is still the ultimate arbiter of proposed Python changes, but Python's user base helps support the language, work on extensions, fix bugs, and so on. In fact, Python development is now a completely open process -- anyone can inspect the latest source-code files or submit patches by visiting a web site (see http://www.python.org for details). As an open source package, Python development is really in the hands of a very large cast of developers working in concert around the world. Given Python's popularity, bus attacks seem less threatening now than they once did; of course, I can't speak for Guido. On the other hand, Python is not really tied to any particular application area at all. For example, Python's integration support makes it useful for almost any system that can benefit from a frontend, programmable interface. In abstract terms, Python provides services that span domains. It is: A dynamic programming language, for situations in which a compile/link step is either impossible (on-site customization), or inconvenient (prototyping, rapid development, system utilities) A powerful but simple programming language designed for development speed, for situations in which the complexity of larger languages can be a liability (prototyping, end-user coding) A generalized language tool, for situations where we might otherwise need to invent and implement yet another "little language" (programmable system interfaces, configuration tools)
  • 44. Programming Python, 2nd Edition, O’Reilly IT-SC book 39 Given these general properties, Python can be applied to any area we're interested in by extending it with domain libraries, embedding it in an application, or using it all by itself. For instance, Python's role as a system tools language is due as much to its built-in interfaces to operating system services as to the language itself. In fact, because Python was built with integration in mind, it has naturally given rise to a growing library of extensions and tools, available as off-the-shelf components to Python developers. Table 1-2 names just a few; you can find more about most of these components in this book or on Python's web site. Table 1-2. A Few Popular Python Tools and Extensions Domain Extensions Systems programming Sockets, threads, signals, pipes, RPC calls, POSIX bindings Graphical user interfaces Tk, PMW, MFC, X11, wxPython, KDE, Gnome Database interfaces Oracle, Sybase, PostGres, mSQL, persistence, dbm Microsoft Windows tools MFC, COM, ActiveX, ASP, ODBC, .NET Internet tools JPython, CGI tools, HTML/XML parsers, email tools, Zope Distributed objects DCOM, CORBA, ILU, Fnorb Other popular tools SWIG, PIL, regular expressions, NumPy, cryptography 1.5 What's Python Not Good For? To be fair again, some tasks are outside of Python's scope. Like all dynamic languages, Python (as currently implemented) isn't as fast or efficient as static, compiled languages like C. In many domains, the difference doesn't matter; for programs that spend most of their time interacting with users or transferring data over networks, Python is usually more than adequate to meet the performance needs of the entire application. But efficiency is still a priority in some domains. Because it is interpreted today,[3] Python alone usually isn't the best tool for delivery of performance-critical components. Instead, computationally intensive operations can be implemented as compiled extensions to Python, and coded in a low-level language like C. Python can't be used as the sole implementation language for such components, but it works well as a frontend scripting interface to them.
  • 45. Programming Python, 2nd Edition, O’Reilly IT-SC book 40 [3] Python is "interpreted" in the same way that Java is: Python source code is automatically compiled (translated) to an intermediate form called "bytecode," which is then executed by the Python virtual machine (that is, the Python runtime system). This makes Python scripts more portable and faster than a pure interpreter that runs raw source code or trees. But it also makes Python slower than true compilers that translate source code to binary machine code for the local CPU. Keep in mind, though, that some of these details are specific to the standard Python implementation; the JPython (a.k.a. "Jython") port compiles Python scripts to Java bytecode, and the new C#/.NET port compiles Python scripts to binary .exe files. An optimizing Python compiler might make most of the performance cautions in this chapter invalid (we can hope). For example, numerical programming and image processing support has been added to Python by combining optimized extensions with a Python language interface. In such a system, once the optimized extensions have been developed, most of the programming occurs at the higher-level Python scripting level. The net result is a numerical programming tool that's both efficient and easy to use. Moreover, Python can still serve as a prototyping tool in such domains. Systems may be implemented in Python first, and later moved in whole or piecemeal to a language like C for delivery. C and Python have distinct strengths and roles; a hybrid approach, using C for compute-intensive modules, and Python for prototyping and frontend interfaces, can leverage the benefits of both. In some sense, Python solves the efficiency/flexibility tradeoff by not solving it at all. It provides a language optimized for ease of use, along with tools needed to integrate with other languages. By combining components written in Python and compiled languages like C and C++, developers may select an appropriate mix of usability and performance for each particular application. While it's unlikely that it will ever be as fast as C, Python's speed of development is at least as important as C's speed of execution in most modern software projects. On Truth in Advertising In this book's conclusion we will return to some of the bigger ideas introduced in this chapter, after we've had a chance to study Python in action. I want to point out up front, though, that my background is in Computer Science, not marketing. I plan to be brutally honest in this book, both about Python's features and its downsides. Despite the fact that Python is one of the most easy-to-use programming languages ever created, there are indeed some pitfalls, which we will examine in this book. Let's start now. Perhaps the biggest pitfall you should know about is this one: Python makes it incredibly easy to throw together a bad design quickly. It's a genuine problem. Because developing programs in Python is so simple and fast compared to traditional languages, it's easy to get wrapped up in the act of programming itself, and pay less attention to the problem you are really trying to solve. In fact, Python can be downright seductive -- so much so that you may need to consciously resist the temptation to quickly implement a program in Python that works, and is arguably "cool," but leaves you as far from a maintainable implementation of your original conception as you were when you started. The natural delays built in to compiled language development -- fixing compiler error messages, linking libraries, and the like -- aren't there
  • 46. Exploring the Variety of Random Documents with Different Content
  • 47. Child labor laws of today. years were put to work for long hours under frightful conditions. Underpaid and underfed, deprived of schooling, they grew up to be physically and intellectually unfit and developed into inferior citizens. [187] Child labor was thought to be cheap, and from the employer’s point of view it was; but in the long run society found it to be incalculably expensive. Unrestricted child labor increased the number of illiterates, promoted the spread of disease and crime, augmented poverty, and bred discontent. The child is the father of the man; and as our children are cared for so will the future manhood and womanhood of the nation be. No fewer than two million persons under fifteen years of age are engaged in some form of wage-earning occupation in the United States today. Since they are unable to protect themselves against overwork and underpayment, the state must see to it that they are treated by their employers with consideration and humanity. The laws relating to child labor differ considerably in the various states; in some the provisions are much stricter than in others. In general the tendency is to prohibit the regular employment of children under fourteen years of age. Many of the states forbid the employment of persons under sixteen years of age in night work or in certain dangerous occupations, such as mining. The hours of labor for persons under sixteen are also limited in some states to not exceeding eight per day. Many other provisions restricting child labor are now in force, and year by year new limitations are being added.[188] In 1916 Congress undertook to place a general restriction on child labor throughout the entire country by passing a law which forbade the transportation and sale in interstate commerce of any goods made in whole or in part by children under a designated age-limit. The Supreme Court of the United States held this law to be unconstitutional, however, declaring that the authority to regulate commerce among the states does not empower Congress to control the conditions of industry within the state boundaries. Congress has since placed a ban upon child labor in another way, namely, by providing that the profits of these industries which employ children shall be taxed more heavily than the profits of those concerns which do not.[189]
  • 48. Some practical difficulties. The arguments for minimum wage laws. Nature of these laws. Causes of unemployment. Minimum Wage Laws.—Investigations into the subject made some years ago disclosed the fact that not only were women and children frequently overworked in industries but that they were often underpaid as well. One reason for this underpayment was that many of the women and children workers lived at home and did not need to be entirely self-supporting. They merely contributed to the general family earnings. They were thus in a position to work for smaller wages than if they were entirely self-dependent. But there were also many thousands of women and children who had to support themselves entirely from their own earnings and to these the low rate of wages meant hardship and suffering. It meant undernourishment, physical break-down, and premature old age. It led to pauperism and immorality. So the laws have once more intervened to protect the well-being of the race against the fruits of industrial injustice by providing that the wages of women and children in industry shall not fall below a certain minimum. Many of the states have put these minimum wage laws upon their statute books. Sometimes the minimum rate of wages is fixed in the law; more often it is determined in the case of each industry by a state board after an investigation. The minimum rate is set at such a point as will enable the wage-earner to be self-supporting. Here, again, the basic principle is that the actual cost of production, including the cost of protecting society against things detrimental to it, should be paid by the public which buys the goods. One practical difficulty connected with the minimum wage plan is that it tends to throw the less efficient employees out of work altogether. The employer who is forced by law to pay a fixed minimum in wages, no matter how unskillful the worker may be, will promptly dismiss all those who do not give him, in work, the worth of their wages. If a minimum wage is established in all industries, where will the least skillful find employment? The Problem of Unemployment.—The greatest of all economic wastes today is that which results from unemployment. The ideal condition would be to have everybody employed all the time. If that could be accomplished
  • 49. Some suggested remedies. How progress toward a solution of the problem is being made. we could produce a great deal more each year at lower cost. Unemployment means that idle men must use what other workers are producing. But it is not possible to do away with unemployment altogether. Some trades are seasonal in character, that is to say, busy at one period of the year and slack during others. In northern regions the building trades, bricklaying, outdoor carpentry, and so on, are in this category. The larger part of the unemployment, however, is due to other than seasonal causes. It is due rather to trade depressions which from time to time cause the shutting down of industrial establishments and it is caused in some degree by the lack of careful planning on the part of the employer. The number of unemployed workers throughout the country varies greatly from time to time. It may be as low as five per cent or as high as forty per cent of the entire number. Various plans for lessening the evils of unemployment have been suggested, but they all present some practical difficulties. Better vocational training would reduce the number of unskilled workers; and it is the unskilled who contribute most largely to the ranks of the unemployed. The establishment of public employment offices has done something to bring workers into touch with available jobs. It is proposed that we have a more careful planning of state and municipal improvements so that the heaviest demand for labor on public works would come at times when unemployment is most prevalent—this, it is urged, would help alleviate the trouble even though it might not go very far in solving the whole problem. Much would be accomplished by the better organization of industrial production and by some scheme of co-operation among employers which would enable workers to be transferred from one industry to another. Great practical obstacles are in the way of doing this on a large scale. Some large concerns have already adopted the plan of setting aside each week a certain percentage of the total pay roll as an unemployment reserve. Then, whenever workers are temporarily out of employment through the slackening of business and not through any fault of their own, a certain weekly wage is paid to them from this reserve. Something will also be
  • 50. The experience of Great Britain and Germany. Unemployment insurance. accomplished in the way of reducing unemployment by better vocational guidance, for young men and women often go into employments which afford no chance of promotion and which they subsequently find to be unsuited to their tastes. Many large industries now bestow great care upon the selection of new employees. All applicants are dealt with through a special official known as the employment manager, whose function it is to make reasonably sure that the applicant is fitted for the position. Foremen and bosses are not allowed to discharge employees at will. The complaints must first be referred for investigation to the employment manager’s office. This plan will also help alleviate unemployment if it becomes general. Unemployment insurance has been tried in a few European countries and has been advocated in America. This plan contemplates that each employer shall contribute to a fund from which a stated wage scale shall be paid to those who remain out of work through no fault of their own, or that the government shall provide such a fund from the proceeds of taxes. It is easy to see that a scheme of this sort might be seriously abused, yet so long as the problem of unemployment remains serious we must strive to find some way of solving it. Old-Age Pensions.—Most wage-earners do not save enough to provide for themselves in old age. The result is that after long years of toil they are dependent upon their children, or must eke out a precarious existence by doing odd jobs, or must be supported by the public poor-relief funds. This is not a desirable state of affairs and in some European countries, notably in Great Britain and in Germany, systems of old-age pensions for workers have been established. In Germany the worker pays a small amount each week into the fund; the employer pays an equal amount and the government pays the rest. In Great Britain the employers and the government pay it all. Every wage-earner, on reaching old age, receives a small weekly allowance for the rest of his days.[190] The cost of an old-age pension system is enormous, but in the long run it is likely to represent real economy. Sooner or later the system will probably be established in this country; the only question is whether, when it comes, the wage-
  • 51. The patriotism of American labor. earner should be required to pay a regular contribution during the years in which he is able to do full work. American Labor and the War.—Among the various factors which helped to win the World War the loyalty and enthusiasm of American labor should be accorded a high place. War always creates a great shortage of workers, partly because so many able-bodied men are taken into the army and partly because of the tremendous need for workers in munition plants and other war industries. During war, therefore, the labor organizations are always in a position to make demands which cannot well be refused. It is quite true that American labor took advantage of its opportunities during the World War; but so did the employers. The wages of labor rose everywhere, as did the profits of industry. Nevertheless it can fairly be said that labor co-operated with the government at all the essential points and produced the uninterrupted flow of materials which was needed to ensure victory. Certain it is that without this co-operation on the part of labor the United States could not have figured so prominently in deciding the ultimate issue of the great conflict. General References Isaac Lippincott, Economic Development of the United States, pp. 491-511; R. T. Ely, The Labor Movement in America, pp. 34-91 (Growth and Present Conditions of Labor Organizations); T. S. Adams and H. L. Sumner, Labor Problems, pp. 461-501 (Labor Laws); F. T. Carlton, Organized Labor in American History, pp. 11-44 (Epochs in the History of Organized Labor); pp. 169-197 (Labor Parties); pp. 198-225 (Ideals of the Wage Earner); R. F. Hoxie, Trade Unionism in the United States, pp. 254-275 (Collective Bargaining); John R. Commons and J. B. Andrews, Principles of American Labor Legislation, pp. 35-90 (Individual Bargaining); Samuel Gompers, American Labor and the War, passim. Group Problems 1. The origin, growth, and aims of labor organizations. The organization of industry before the Industrial Revolution. Rise of the factory system. Creation of a labor class. Early conditions of factory employment. Beginnings of labor organizations. Early attitude of the law and the courts. Growth of labor organizations during the past half century. Central organizations and national
  • 52. bodies. Present-day aims of labor organizations—economic, social, and political. Specific features of organized labor’s program. Labor as a factor in politics. The movements for industrial democracy. References: T.S. Adams and H.L. Sumner, Labor Problems, pp. 214-279; Sidney Webb, History of Trade Unionism, pp. 1-56; 431-541; Mary Beard, Short History of the American Labor Movement, pp. 47-79; F. T. Carlton, Organized Labor in American History, pp. 11-44; 198-225; R. F. Hoxie, History of Trade Unionism in the United States, pp. 211-252 (The Law in Relation to Labor); John R. Commons (editor), History of Labor in the United States, passim; R. T. Ely, The Labor Movement in America, pp. 34-91; P. F. Brissenden, History of the I. W. W., pp. 83-112 (The I. W. W. vs. the A. F. of L.). 2. The American Federation of Labor: its history, aims, and achievements. References: Samuel Gompers, American Labor and the War, pp. 186-196; John Mitchell, Organized Labor, pp. 397-406; F. T. Carlton, History and Problems of Organized Labor, pp. 75-82; Mary R. Beard, Short History of the American Labor Movement, pp. 86-149; G. G. Groat, Organized Labor in America, pp. 82-99; Helen Marot, American Labor Unions, pp. 11-28. 3. The arbitration of industrial disputes. References: T. S. Adams and Helen Sumner, Labor Problems, pp. 295-332; Sidney Webb, Industrial Democracy, pp. 222-246; N. P. Gilman, Methods of Industrial Peace, pp. 301-345; R. T. Ely, The Evolution of Industrial Society, pp. 374-397; John Mitchell, Organized Labor, pp. 337-346; F. W. Taussig, Principles of Economics, Vol. II, pp. 303-322. 4. The general principles of labor legislation. References: W. S. Jevons, The State in Relation to Labor, pp. 1-32; F. W. Taussig, Principles of Economics, Vol. II, pp. 285-302; John R. Commons and J. B. Andrews, Principles of Labor Legislation, pp. 1-34; H. S. Person, Labor Laws and Their Enforcement, passim. Short Studies 1. The four epochs in the history of organized labor. F. T. Carlton, Organized Labor in American History, pp. 11-44. 2. Labor and politics. F. T. Carlton, History and Problems of Organized Labor, pp. 169-197. 3. The Knights of Labor: why they failed. Mary R. Beard, Short History of the American Labor Movement, pp. 116-126. 4. The right to strike. John Mitchell, Organized Labor, pp. 299-323. 5. Collective bargaining. Final Report of the U. S. Industrial Commission, pp. 843-847. 6. The use of injunctions in labor disputes. G. L. Bolen, Getting a Living, pp. 548-580; J. R. Commons, Trade Unionism and Labor Problems, pp. 156-163. 7. The Kansas plan. H. J. Allen, The Party of the Third Part, pp. 16-91. 8. Workmen’s compensation. John R. Commons and J. B. Andrews, Principles of American Labor Legislation, pp. 356-385. See also the publications on this subject issued by the National Industrial Conference Board.
  • 53. 9. Women and children in industry. T. S. Adams and H. L. Sumner, Labor Problems, pp. 19-67. 10. The problem of unemployment. E. T. Towne, Social Problems, pp. 140- 159; W. H. Beveridge, Unemployment, 3d ed., pp. 1-15 (Great Britain). 11. Profit sharing as a solution of industrial problems. T. S. Adams and H. L. Sumner, Labor Problems, pp. 333-378. 12. Old age pensions. W. H. Dawson, Social Insurance, pp. 128-165; F. W. Lewis, State Insurance, pp. 148-170. Questions 1. Explain why labor organizations came into existence during the nineteenth century. On the whole have they been a benefit to industry or not? Give your reasons. 2. Give some reasons for expecting trade unions to be stronger in certain employments than in others. In which of the following employments would you expect the unions to be strong, and in which would you expect them to be weak: (a) railroading; (b) domestic service; (c) school teaching; (d) farming; (e) mining; (f) steel-making? Give reasons for your expectations in each case. 3. With what points in the program of the American Federation of Labor do you agree and with what ones do you disagree? 4. The closed shop is sometimes criticised as being “un-American” and the open shop has been called the “American plan”. What does this mean? 5. Are there any employments, public or private, in which strikes should not be permitted? 6. Why should the consumer pay the costs of all industrial accidents? Explain how he does so where workmen’s compensation acts have been passed. 7. In your opinion would the legislature be justified in limiting to eight hours per day the labor of (a) women in candy factories; (b) men who work on farms; (c) men who work in coal mines; (d) physicians; (e) waitresses in hotels; (f) female servants; (g) members of the fire-protection service in cities; (h) motormen on street cars? Give your reasons in each case. 8. Give your views as to the minimum age at which any person should be permitted to engage in regular employment for wages. At what age should employment in night work be permitted? Should persons under fourteen years of age be allowed to work for wages after school hours, on Saturdays, and during vacations? 9. A girl of sixteen has graduated from grammar school and could obtain a position as clerk in a millinery store at eight dollars a week. She is living at home and does not have to support herself. But the minimum wage for clerks in stores happens to be ten dollars per week and the owner will not pay so much. Is there any injustice here? 10. How can the evil of unemployment be reduced? What abuses might arise in connection with unemployment insurance? Who pays the cost of unemployment
  • 54. now? Argue whether we should or should not place industrial unemployment on the same basis as industrial accidents. Topics for Debate 1. The demand for collective bargaining is (or is not) justified. 2. A plan of old-age pensions, like that now maintained in Great Britain, should be established in the United States.
  • 55. Money supplants barter. CHAPTER XXII CURRENCY, BANKING, AND CREDIT The purpose of this chapter is to explain what money is, what purposes it serves, how banks conduct their business, and how credit facilitates trade. The Origin of Money.—The use of money is one of the marks of civilization. In primitive communities money was unknown. Buying and selling was by barter, the exchange of one commodity for another. The man with too much corn exchanged corn for cattle or for a boat or for skins with which to clothe himself. But exchange by barter is a slow and clumsy method because it means that two persons must be found each of whom wants exactly what the other has to sell, a thing which does not easily happen. With the growth of trade, accordingly, it became necessary to find a medium of exchange, in other words some single commodity which is so readily exchangeable for all other commodities that it can be used to facilitate buying and selling. Some of the Indians of North America used the ends of shells, or wampum, for this purpose. The early colonists in Virginia chose tobacco as a temporary medium of exchange, it being in universal demand. People accepted tobacco in exchange for things which they wished to sell, and gave tobacco for things which they desired to buy. This was not because they wanted tobacco for their own use but because of all commodities in the colony tobacco was the most easy to exchange for other things at a moment’s notice. No ordinary form of merchandise, however, makes an entirely satisfactory medium of exchange and all of them in time gave way to the precious metals, gold and silver, which are now everywhere used for this purpose.[191]
  • 56. 1. Value. 2. Stability. 3. Convenience. Money as a standard of value and a measure of deferred payments. The qualities which money must have: The Functions which Money Serves.— Money, however, serves not only as a medium of exchange but as a standard of value and a measure for future payments. Money is the common denominator by means of which we express the value of different commodities. If money were not in existence, how could we state the value of anything? It would be of little avail to say that a suit of clothes is worth ten hats, for this would merely beg the question: How much is a hat worth? Money performs the function of providing a uniform scale into which all values can be translated. When we say, therefore, that a suit of clothes is worth forty dollars and that hats are worth four dollars apiece we are measuring both commodities according to the same standard of value. Money also facilitates the use of credit by providing a measure for deferred payments. People cannot well agree to indefinite future obligations; they must know exactly what a debt amounts to. The use of money enables men to borrow today with the understanding that they will repay the same amount at some future date. Characteristics of Money.—Gold and silver are best adapted to facilitate exchange because they possess, in high degree, certain qualities which money must have in order to fulfil its functions properly. What are these qualities? To serve acceptably as money a substance must have, in the first place, some value in itself; it must therefore have utility as a basis of value. A worthless substance, which nobody wants, would not do. Second, it must not only have value but stability of value. To serve efficiently as money a metal must not be subject to wide and frequent fluctuations in what it is worth. A substance which might be worth much today and little tomorrow would not be satisfactory. Gold and silver, being produced in limited quantities, are more nearly stable in value than any other metals, gold being particularly so. Third, the metal used as money must possess relatively high value in proportion to its bulk so that it can be easily passed from hand to hand. There was a tradition in ancient Greece that Lycurgus compelled the Lacedaemonians to use iron money in order that its weight might
  • 57. 4. Durability. 5. Uniformity. 6. Divisibility. 7. Cognizability. Gold is the American standard of values. deter them from overmuch trading. If iron were used as currency today a dime would weigh more than a pound.[192] In a word the metal used as money must be portable, easy to carry around. Fourth, it must be relatively indestructible, not subject to rapid decay or rusting. Gold and silver satisfy this requirement, for time does not destroy their value nor do they suffer much wear and tear through handling. It is believed that some of the gold which is in the coinage of European countries today served as money in the time of the Romans. Fifth, it must be homogeneous, that is, it must not vary in quality, otherwise equal amounts of it would not have the same value. In order that we may reckon things in terms of money the units must be equal and similar so that twice one will always make two. If we were to use diamonds as money, it would not always happen that two stones would be worth exactly twice as much as one. Sixth, it must be easily divisible without loss of value, for we need small units of money as well as large ones. One great difficulty which primitive people found in using the skins of animals as money was that they could not be cut into portions without destroying their value altogether. Nobody would take, for example, a quarter of a skin in payment for a basketful of corn. But gold and silver can be divided at will and yet retain an exactly proportionate value. Finally, it must be a metal or other substance the genuineness of which can be easily determined. If every person who receives money had to scrutinize, weigh, and test it, the processes of trade would be intolerably delayed.[193] Gold and silver may not themselves be readily cognizable by the uninitiated, but they are easy to stamp into coins with a stamp or design and this impression cannot be easily counterfeited. The various countries of the world adopted gold and silver as their chief media of exchange because these metals fulfil in the largest degree the foregoing requirements. For small units of currency nickel and bronze are utilized because subsidiary coins of gold and silver would be too small. The Coinage of the United States.—In the United States gold is the standard of values. This does not mean that gold is circulated from
  • 58. The United States mints. In 1792. In 1834. In 1873. The ratio between gold and silver. hand to hand in every transaction, but merely that all economic values are expressed in terms of gold coin. The actual payments may be made in paper notes, or in silver, nickel, or copper coins. The monetary system of the United States is based upon the decimal system, which was adopted in 1784 at the suggestion of Thomas Jefferson. This means that we reckon in fractions and multiples of ten—ten cents one dime, ten dimes one dollar, and ten dollars one eagle. For convenience there are also additional coins, such as nickels, quarter dollars, half dollars, and half-eagles. No gold dollars are now coined, as they were found to be too small for convenience. [194] The mint has also ceased coining quarter eagles but continues to make five, ten, and twenty dollar gold pieces although these coins remain for the most part in the banks where they are held as reserves. Very little gold coin is in circulation anywhere in the world today. The coining of money is wholly within the jurisdiction of the national government; no state is allowed to make or issue coins. The making of coins takes place at four mints, which are located at Philadelphia, New Orleans, Denver, and San Francisco.[195] If you look at the reverse side of a recently minted coin, you will find, near the base, a small letter indicating the mint at which the coin was struck; if there is no such letter, the coin was minted at Philadelphia. The Controversy over Bimetallism.—In 1792, when the first American mint was established, Congress provided by law that there should be two monetary units, the gold dollar and the silver dollar—the ratio between the two, in terms of weight, being fixed at fifteen to one. Any person bringing gold or silver bullion to the mint was entitled to have it made into coins at this ratio, which corresponded to the relative market value of the two metals in 1792. Silver eventually cheapened in relation to gold, however, and in time only silver bullion came to be coined. So Congress in 1834 reduced the weight of the gold dollar and made the ratio sixteen to one. This, in turn, proved to be an under-valuation of silver, and no silver now came to the mint to be coined.[196] In 1873, after silver dollars had practically dropped out of
  • 59. In 1893. Final settlement of the question in 1900. Our early experience with circulation Congress abolished the free coinage of silver altogether. [197] Presently, however, there was a popular demand for a resumption of silver coinage and the minting of silver dollars was recommenced,[198] but only on a limited scale; and in 1893 it was once more abandoned.[199] This action on the part of Congress raised a great hue and cry in certain sections of the country, especially in the South and West. Free coinage of silver was desired not only by owners of mines who had silver to sell but by large numbers of farmers who believed that gold was becoming too scarce to serve as the sole standard of value. Scarcity of gold meant scarcity of money, and scarcity of money meant low prices for wheat. If money were plentiful, prices would go higher, and the way to get more money was to coin into dollars all the silver that would come to the mint. That was the farmers’ argument. The “Cross of Gold” Campaign.—The leaders of the Democratic party took advantage of this widespread agricultural grievance. At the national convention of that party, held at Chicago in the summer of 1896, Mr. W. J. Bryan swept the delegates off their feet with his denunciation of the “few financial magnates who corner the money of the world” and his plea for the poor man’s dollar. “You shall not press upon the brow of labor this crown of thorns”, he declaimed. “You shall not crucify mankind upon a cross of gold.” The delegates, amid tumultuous cheering and enthusiasm, thereupon nominated the young orator from Nebraska as their candidate for President and made the free coinage of silver at a ratio of “sixteen to one” a fundamental part of the Democratic platform in the election campaign. But Bryan was overwhelmingly defeated and the clamor for free silver soon subsided. In 1900 Congress passed the Currency Act, which declared gold to be the sole standard and directed the secretary of the treasury to maintain all other forms of currency at a parity with gold. This means that every silver dollar, whether the silver which it contains be worth a dollar or not, is guaranteed by the national government to be worth a gold dollar. Paper Money.—Our experience with paper money goes back to colonial days when bills of
  • 60. paper currency. What the constitution provides as regards paper money. The seven kinds of paper money in use. credit were issued by Massachusetts to pay the costs of the expedition against Quebec in 1690. But no great amounts were issued until the Revolutionary War; then the various state governments as well as the Continental Congress printed and issued notes to the par value of nearly half a billion dollars. In the earlier years of the war this paper currency circulated at its face value although there was no gold or silver reserve behind it; but as the struggle dragged on and notes by the million kept being issued they began to depreciate until eventually this continental paper currency was worth only a fraction of a cent per dollar. Hence the origin of the slang expression “not worth a continental”. The notes for the most part were never redeemed; they merely became worthless and passed out of circulation. Naturally this experience made the people averse to paper money and when the constitution of the United States was framed it contained a provision that “no state shall emit bills of credit (or) make anything but gold and silver coin a tender in payment of debts”. It was strongly urged that the national government should also be prohibited from issuing paper money, but in the end it was decided not to make any express prohibition, so the constitution is silent as regards the authority of the national government to emit bills of credit. It neither gives this power nor denies it. In due course, however, Congress authorized the issue of legal-tender notes or greenbacks, and the Supreme Court upheld its right to do this on the ground that the constitution expressly gives Congress the power to borrow money and that the issue of paper money is a reasonable method of borrowing. But although the national government has itself the legal right to issue paper money, either with or without a reserve behind it, most of the paper money now in circulation is issued by the federal reserve board or by the federal reserve banks under authority granted by Congress. Paper Notes now in Circulation.—There are several kinds of paper notes now in circulation. [200] These include silver certificates, gold certificates, treasury notes, and greenbacks issued directly by the national government, national bank notes, federal reserve notes, and
  • 61. Inconvertible paper money. Paper money has some advantages in convenience and cheapness. Why not abolish money? federal reserve bank notes. The provisions for the redemption of these different types of paper money vary greatly, and each is protected by a different reserve, but in actual fact the holder of any unit of paper money can obtain gold for it if he so desires. This is true even of the silver certificates which, strictly speaking, are redeemable only in silver dollars. The arrangements under which the national banks, the federal reserve banks, and the federal reserve board are permitted to issue paper money will be discussed presently. Why do we have paper money? Chiefly because it is, in many respects, more convenient for use than metallic money. In large amounts it is not so bulky as silver or gold would be. There is also the advantage that when paper money wears out it can be cheaply replaced. If gold coins were continually in circulation from hand to hand, they would gradually wear down and the monetary loss would be considerable. Hence it is better to keep the gold in the bank vaults and circulate the paper, which represents gold, in its stead. But a sound system of paper money should always provide for the redemption of the notes, which means that the notes should have an adequate reserve behind them. This reserve should be in gold or in the equivalent of gold. Unredeemable paper money, issued without an adequate reserve behind it, leads practically always to depreciation and thereby to heavy losses on the part of the people who have taken the money in good faith. That was what happened in the case of the assignats of the French Revolution, the continental currency in the American Revolution, and the paper money of several European countries during the World War.[201] It is folly to try to finance a war or any other national enterprise by issuing fiat currency, as it is called, which is paper currency with only the word of the government and no substantial reserve behind it. Better tax the people outright than make them take money as legal tender which is not worth what it purports to be.[202] Radicals sometimes say: “Let us do away with money altogether”. Instead of money, they say, we might use “labor checks”, each check representing a given
  • 62. amount of labor. One hour of labor, let us say, would then be the standard of value instead of 23.2 grains of gold. This arrangement, however, would not abolish money, but only change the nature of the basis upon which the value of money is calculated. The labor checks would be money in every sense of the word. There is only one way to abolish money and that is to go back to barter.
  • 63. 1. As institutions of deposit.] 2. As agencies for loaning money. 3. Sometimes also as issuers of paper money. 4. To transfer funds from one place to another. Banks serve: The Banking System What Functions do Banks Perform?— Banks are established and maintained to satisfy certain needs which arise wherever men carry on extensive trade with one another. In the first place when money is accumulated by people in the course of their business some safe place is needed to keep it. Banks, therefore, serve as institutions of deposit. In the second place, as business develops, it becomes necessary for people to borrow money. Banks facilitate this borrowing. Their two primary functions are to receive deposits and to make loans. But in order that they may perform these two primary functions to the best advantage the banks have assumed other subsidiary functions as well. Frequently they issue bank notes, or the bank’s own promises to pay, for use in general circulation. They sell drafts or bills of exchange, thus enabling people to transfer funds from one city or country to another without the trouble and risk of sending the actual money. As a rule they provide safe-deposit vaults in which customers, on payment of a small sum, are permitted to keep their valuables. These vaults are fire-proof and burglar-proof. Banks also collect money which may be due to a customer from someone elsewhere. They help the national and state governments to sell their bonds. Frequently they act as trustees, holding property for children until they grow up or for other persons who are unable to look after the property for themselves. Without banks it would be difficult, if not impossible, to carry on the operations of modern business. The Early American Banking System.—The national constitution contains no mention of banks or banking. Hence it was assumed that the power to charter banks would rest with the states. The states assumed this authority but the national government desired to exercise it also, and during the first thirty years of its existence established two great banks, both of which became unpopular and ultimately went out of existence. The first Bank of the United States, established in 1791, ceased to do business in 1811; the second
  • 64. Their functions. Their reserves. Present organization of the national banks. bank, chartered in 1816, incurred the wrath of President Andrew Jackson and went to the wall in 1836.[203] From this date to the Civil War the state banks, of which a large number were established in all parts of the country, had the field to themselves. The National Banking Act of 1863.—During the Civil War, however, the national government encountered great difficulty in raising funds. When it issued bonds the people would not buy them readily. The state banks showed very little interest in marketing them. So Congress, in this emergency, decided to establish a system of national banks in order to facilitate the sale of war bonds. The National Banking Act, passed in that year, laid a heavy tax upon the paper money of all state banks, with intent to drive this currency out of circulation. It then provided that any bank chartered by the national government might issue untaxed paper money provided it bought United States bonds to a designated amount and deposited these bonds in Washington as security. In other words the Act of 1863 aimed to provide a uniform system of bank notes throughout the country, these notes to be backed by government bonds. The plan worked well and its main provisions have been retained to this day. National banks are owned by private individuals who subscribe the capital stock. These stockholders, or shareholders, elect the bank’s officers, who in turn manage the business. The profits go to the shareholders in the form of annual dividends. Each national bank must buy a designated amount of United States bonds and these bonds are deposited in Washington. In return the bank receives an equal amount of paper notes, with its own name engraved thereon, and these notes the bank pays out over its counters, thus putting them in general circulation. If the bank should become insolvent, the government would redeem the notes since it holds the bonds as security. The national banks receive money on deposit, make loans, and perform the various other banking functions. They are strictly regulated by national law; they must make periodic reports and are frequently inspected by officials from Washington. One requirement is that they shall always maintain a certain
  • 65. State banks and trust companies. Defects of the national banking system due to the concentration of reserves and lack of flexibility. How the Federal Reserve system remedies these defects. “reserve” so that they may be in a position to make all payments which may be called for by their customers. The supervision of the national banks is in the hands of an official known as the Comptroller of the Currency, who is appointed by the President. In addition to the national banks there are state banks and trust companies throughout the country operating under state charters. These institutions do not issue paper money but perform all the other banking functions.[204] Their business is regulated by the laws of the state in which they are located and they are supervised by state officials. The laws relating to state banks and trust companies differ considerably from state to state. The Federal Reserve Banks.—Although the national banking system worked pretty well for fifty years after its establishment, certain defects came to be recognized. One of these defects, in actual practice, was the necessity of always keeping available a “reserve” amounting to a certain percentage of each bank’s total deposits. It was not necessary to keep this reserve in the bank’s own vaults; a part of it might be placed upon deposit in larger banks where it would draw interest. As matters turned out, a considerable portion of the reserves was usually deposited with large banks in New York City. In times when business was good and money plentiful, this arrangement worked very well, but when periods of business depression arrived and money became scarce every small bank naturally drew upon its reserve deposits in the larger banks, which found difficulty in paying them all at the same time. Moreover, it was found from experience that during times of business prosperity the country needed a large increase in paper money while the national banking system, as established in 1863, proved too rigid to meet the business needs of the country. In 1913, accordingly, Congress made provision for the establishment of a Federal Reserve system which does not displace but supplements the operations of the national banks. By an act passed in that year provision was made for the
  • 66. The Federal Reserve Board. How they give flexibility to the whole banking system of the country. Functions of the Federal Reserve Banks. establishment of twelve federal reserve districts, with a federal reserve bank in each. The capital stock of each federal reserve bank is contributed by national or state banks within the districts, these contributors being then known as “member banks”. The national government also subscribes a part of the capital stock when necessary. Each federal reserve bank is controlled by officials, some of whom are elected by the member banks and some appointed by the national government through a body known as the Federal Reserve Board. This board is composed of the Secretary of the Treasury, the Comptroller of the Currency, and five other members appointed by the President. These federal reserve institutions are bankers’ banks. They do business with banks only, not with individuals. They receive deposits from banks and lend money to banks. The member banks now keep with them a portion of their reserves. In this way the reserves are mobilized at twelve different financial centers where they can be readily drawn upon.[205] The Federal Reserve Board has authority to increase or decrease the percentage of reserves which the member banks are required to maintain, thus giving the reserve system a large degree of flexibility. Whenever a member bank needs additional paper money for circulation it goes to the federal reserve bank of its district and deposits any sound “collateral”, that is to say, any acceptable security, and receives federal reserve notes of like value in return. This collateral may be in the form of government bonds or it may be, and more often is, “commercial paper”. By commercial paper is meant the notes or other obligations of corporations and individuals which have been given to the member banks in return for loans made to such corporations and individuals. The federal reserve banks are authorized to issue federal reserve notes, to an unlimited extent on the security of this collateral provided they also keep a gold reserve amounting to forty per cent of the total notes issued. In addition they are empowered to issue federal reserve bank notes secured by United States bonds in the same way as national bank notes are
  • 67. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookfinal.com